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()
顯示效果以下所示: