Matplotlib是一个强大的Python**绘图**和**数据可视化**的工具包。html
# 安装方法 pip install matplotlib # 引用方法 import matplotlib.pyplot as plt # 绘图函数 plt.plot() # 展现图像 plt.show()
执行后显示效果以下:python
plot函数:用于绘制折线图。数组
线型linestyle:‘-’是实线、'--'是线虚线、‘-.’是线点虚线等、‘:’是点虚线。函数
import matplotlib.pyplot as plt plt.plot([1,2,3,4],[2,3,1,8]) # 绘制折线图 plt.show()
显示效果以下所示:工具
点型marker:v、^、s、*、H、+、x、D、o.....源码分析
其中是o是圆点、v是下三角、D是菱形、H是六边形等。学习
plt.plot([1,2,3,4],[2,3,1,8], 'o') # 参数o,绘制点图 plt.show()
显示效果以下所示:this
plt.plot([1,2,3,4],[2,3,1,8], 'o-') # 参数o-,绘制点线图 plt.show()
显示效果以下所示:spa
颜色color:b、g、r、y、k、w......3d
plt.plot([1,2,3,4],[2,3,2,7], 'o:r') # 红色线 plt.show()
显示效果以下所示:
plt.plot([1,2,3,4],[2,3,2,7], color='purple') # 紫色线 plt.show()
显示效果以下所示:
生成几个plot.plot()就能够在一个图里绘制多少个曲线。
plt.plot([1,2,3,4],[2,3,2,7], color='red') plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o') plt.show()
显示效果以下所示:
前面学习的plt.plot()和plt.show()函数只是绘图和显示图像。但若是要设置标题、名称等图像标注就须要用到其余函数了。
# 引用方法 import matplotlib.pyplot as plt # 绘图函数 plt.plot([1,2,3,4],[2,3,2,7], color='red') plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o') plt.title('Matplotlib Test Plot') # 设置图像标题 # 展现图像 plt.show()
显示效果以下所示:
# 引用方法 import matplotlib.pyplot as plt # 绘图函数 plt.plot([1,2,3,4],[2,3,2,7], color='red') plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o') plt.title('Matplotlib Test Plot') plt.xlabel('Xlabel') plt.ylabel('Ylabel') # 展现图像 plt.show()
显示效果以下所示:
# 引用方法 import matplotlib.pyplot as plt # 绘图函数 plt.plot([1,2,3,4],[2,3,2,7], color='red') plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o') plt.title('Matplotlib Test Plot') plt.xlabel('Xlabel') plt.ylabel('Ylabel') plt.xlim(0,5) # 设置x轴最小值0,最大值5 plt.ylim(0,10) # 设置y轴最小值0,最大值10 # 展现图像 plt.show()
显示效果以下所示:
# 引用方法 import matplotlib.pyplot as plt import numpy as np # 绘图函数 plt.plot([1,2,3,4],[2,3,2,7], color='red') plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o') plt.title('Matplotlib Test Plot') plt.xlabel('Xlabel') plt.ylabel('Ylabel') plt.xlim(0,10) plt.ylim(0,10) # plt.xticks(0,2,4) # 设置x轴刻度 plt.xticks(np.arange(0,11,2)) # 用numpy设置x轴刻度 # 展现图像 plt.show()
显示效果以下所示:
刻度还能够自定义字段显示:
# 引用方法 import matplotlib.pyplot as plt import numpy as np # 绘图函数 plt.plot([1,2,3,4],[2,3,2,7], color='red') plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o') plt.title('Matplotlib Test Plot') plt.xlabel('Xlabel') plt.ylabel('Ylabel') plt.xlim(0,10) plt.ylim(0,10) # plt.xticks(0,2,4) # 设置x轴刻度 plt.xticks(np.arange(0,11,2), ['a','b','c','d','e','f']) # 用numpy设置x轴刻度 # 展现图像 plt.show()
显示效果以下:
在plt.plot()中设置label,便可使用plt.legend()函数设置曲线图例。
# 引用方法 import matplotlib.pyplot as plt import numpy as np # 绘图函数 plt.plot([1,2,3,4],[2,3,2,7], color='red', label='Line A') plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o', label='Line B') plt.title('Matplotlib Test Plot') plt.xlabel('Xlabel') plt.ylabel('Ylabel') plt.legend() # 曲线图例 # 展现图像 plt.show()
显示效果以下:
import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('601318.csv', parse_dates=['date'], index_col='date')[['open','close','high','low']] # 读取csv文件,使用date做为索引列 df.plot() plt.show()
显示效果以下所示:
# 引用方法 import matplotlib.pyplot as plt import numpy as np x = np.linspace(-100,100,10000) # 起点、终点、分多少份 y1=x y2=x**2 y3=3*(x**3)+5*(x**2)+2*x+1 plt.plot(x, y1, color='red', label='y=x') plt.plot(x, y2, color='green', label='y=x**2') plt.plot(x, y3, color='purple', label='y=3*(x**3)+5*(x**2)+2*x+1') plt.ylim(-1000,1000) # 因为紫色线增加过快,图片显示会致使红色和绿色重合 plt.xlim(-100,100) plt.legend() # 展现图像 plt.show()
显示效果以下所示:
Matplotlib提供了不少函数来支持不一样的图类型,以下所示:
函数 | 说明 |
plt.plot(x,y,fmt,...) | 坐标图 |
plt.boxplot(data,notch,position) | 箱型图 |
plt.bar(left,height,width,bottom) |
条形图 |
plt.barh(width,bottom,left,height) | 横向条形图 |
plt.polar(theta, r) | 极坐标图 |
plt.pie(data, explode) | 饼图 |
plt.psd(x,NFFT=256,pad_to,Fs) | 功率谱密度图 |
plt.specgram(x,NFFT=256,pad_to,F) | 谱图 |
plt.cohere(x,y,NFFT=256,Fs) | X-Y相关性函数 |
plt.scatter(x,y) | 散点图 |
plt.step(x,y,where) | 步阶图 |
plt.hist(x,bins,normed) | 直方图 |
相关文档参见:matplotlib官网
import matplotlib.pyplot as plt import pandas as pd # 画布:figure fig = plt.figure() # 生成画布 # 图:subplot ax1 = fig.add_subplot(2,2,1) # 两行两列第一个图 ax1.plot([1,2,3,4],[5,6,7,8]) ax2 = fig.add_subplot(2,2,2) # 两行两列第二个图 ax2.plot([1,4,2,3],[2,6,3,8]) fig.show()
显示效果以下所示:
import matplotlib.pyplot as plt import pandas as pd # 画布:figure fig = plt.figure() # 生成画布 # 图:subplot ax1 = fig.add_subplot(2,1,1) # 两行一列第一个图 ax1.plot([1,2,3,4],[5,6,7,8]) ax2 = fig.add_subplot(2,1,2) # 两行一列第二个图 ax2.plot([1,4,2,3],[2,3,4,6]) fig.show()
显示效果以下所示:
subplots_adjust()函数源码以下所示:
def subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None): """ Update the :class:`SubplotParams` with *kwargs* (defaulting to rc when *None*) and update the subplot locations. """ if self.get_constrained_layout(): self.set_constrained_layout(False) warnings.warn("This figure was using constrained_layout==True, " "but that is incompatible with subplots_adjust and " "or tight_layout: setting " "constrained_layout==False. ") self.subplotpars.update(left, bottom, right, top, wspace, hspace) for ax in self.axes: if not isinstance(ax, SubplotBase): # Check if sharing a subplots axis if isinstance(ax._sharex, SubplotBase): ax._sharex.update_params() ax.set_position(ax._sharex.figbox) elif isinstance(ax._sharey, SubplotBase): ax._sharey.update_params() ax.set_position(ax._sharey.figbox) else: ax.update_params() ax.set_position(ax.figbox) self.stale = True
import matplotlib.pyplot as plt import numpy as np data = [32,48,21,100] labels = ['Jan', 'Feb', 'Mar', 'Apr'] # 柱状图 plt.bar(np.arange(len(data)), data , color='blue', width=0.5) plt.xticks(np.arange(len(data)), labels) plt.show()
显示效果:
import matplotlib.pyplot as plt plt.pie([10,20,28,42], labels=['England','German','USA','China'], autopct='%.2f%%',explode=[0,0.1,0,0.1]) # labels设置标签,autopct显示百分比,explode设置突出程度 # plt.axis('equal') # 设置图片朝向 plt.show()
显示效果:
matplotlib.finanace子包中有许多绘制金融相关图的函数接口。
绘制K线图:matplotlib.finance.candlestick_ochl函数。
import matplotlib.finance as fin
可是从matplotlib 2.2.0版本开始,matplotlib.finance已经从matplotlib中剥离了,须要单独安装mpl_finance这个包了。
能够anaconda中下载mpl-finance包等方法下载。
import mpl_finance as fin
def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0): """ Plot the time, open, close, high, low as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown Parameters ---------- ax : `Axes` # 图对象 an Axes instance to plot to quotes : sequence of (time, open, close, high, low, ...) sequences # 二维数组 As long as the first 5 elements are these values, the record can be as long as you want (e.g., it may store volume). time must be in float days format - see date2num # datetime要转化为小数类型时间戳 width : float # k线宽度 fraction of a day for the rectangle width colorup : color # 阳线颜色 the color of the rectangle where close >= open colordown : color # 阴线颜色 the color of the rectangle where close < open alpha : float # 矩形的透明度 the rectangle alpha level Returns ------- ret : tuple returns (lines, patches) where lines is a list of lines added and patches is a list of the rectangle patches added """ return _candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, alpha=alpha, ochl=True)
def date2num(d): """ Convert datetime objects to Matplotlib dates. Parameters ---------- d : `datetime.datetime` or `numpy.datetime64` or sequences of these Returns ------- float or sequence of floats Number of days (fraction part represents hours, minutes, seconds, ms) since 0001-01-01 00:00:00 UTC, plus one. Notes ----- The addition of one here is a historical artifact. Also, note that the Gregorian calendar is assumed; this is not universal practice. For details see the module docstring. """ if hasattr(d, "values"): # this unpacks pandas series or dataframes... d = d.values if not np.iterable(d): if (isinstance(d, np.datetime64) or (isinstance(d, np.ndarray) and np.issubdtype(d.dtype, np.datetime64))): return _dt64_to_ordinalf(d) return _to_ordinalf(d) else: d = np.asarray(d) if np.issubdtype(d.dtype, np.datetime64): return _dt64_to_ordinalf(d) if not d.size: return d return _to_ordinalf_np_vectorized(d)
# import matplotlib.finance as fin import pandas as pd import matplotlib.pyplot as plt import mpl_finance as fin from matplotlib.dates import date2num # 用于将datetime对象转化为浮点数 # 读取csv文件中保存的行情数据,使用date做为索引列 # na_values将None字符串解释为缺失值 df = pd.read_csv('601318.csv', parse_dates=['date'], index_col='date', na_values=['None'])[['open','close','high','low']] # 添加time这一列 df['time'] = date2num(df.index.to_pydatetime()) # 将df转换为数组才能传递给candlestick_ochl()函数 arr = df[['time','open','close','high','low']].values # print(df) ''' open close high low time date 2007-03-01 21.878 None 22.302 20.040 732736.0 2007-03-02 20.565 None 20.758 20.075 732737.0 ''' # 因为candlestick_ochl函数中要求有Axes,所以建立画布和子图 fig = plt.figure() # 画布 ax = fig.add_subplot(1,1,1) # 子图 # candlestick_ochl()与candlestick_ohlc()的区别主要是执行顺序 fin.candlestick_ochl(ax, arr) # fig.grid() fig.show()
显示效果以下所示: