###序言: Python的可視化工具,如下截圖,均以展現圖表實例,如需瞭解部分對象的輸出結果,可參照我Github上的代碼,3Q🌹python
####【課程3.1】 Matplotlib簡介及圖表窗口 Matplotlib → 一個python版的matlab繪圖接口,以2D爲主,支持python、numpy、pandas基本數據結構,運營高效且有較豐富的圖表庫git
圖表窗口1 → plt.show()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 圖表窗口1 → plt.show()
plt.plot(np.random.rand(10))
plt.show()
# 直接生成圖表
複製代碼
圖表窗口2 → 魔法函數,嵌入圖表
# 圖表窗口2 → 魔法函數,嵌入圖表
% matplotlib inline
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y)
# 直接嵌入圖表,不用plt.show()
# <matplotlib.collections.PathCollection at ...> 表明該圖表對象
複製代碼
% matplotlib notebook s = pd.Series(np.random.randn(100)) s.plot(style = 'k--o',figsize=(10,5))github
![3.png](https://upload-images.jianshu.io/upload_images/2330091-4bc58a4f1bdacb44.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### 圖表窗口4 → 魔法函數,彈出matplotlib控制檯
複製代碼
% matplotlib qt5 df = pd.DataFrame(np.random.rand(50,2),columns=['A','B']) df.hist(figsize=(12,5),color='g',alpha=0.8)spring
#plt.close()數組
#plt.gcf().clear()bash
PS:這裏須要用代碼調試
<br>
####【課程3.2】 圖表的基本元素
    圖表內基本參數設置
>##### 圖名,圖例,軸標籤,軸邊界,軸刻度,軸刻度標籤等
複製代碼
df = pd.DataFrame(np.random.rand(10,2),columns=['A','B']) fig = df.plot(figsize=(6,4))數據結構
plt.title('Interesting Graph - Check it out') # 圖名 plt.xlabel('Plot Number') # x軸標籤 plt.ylabel('Important var') # y軸標籤dom
plt.legend(loc = 'upper right')svg
plt.xlim([0,12]) # x軸邊界 plt.ylim([0,1.5]) # y軸邊界 plt.xticks(range(10)) # 設置x刻度 plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2]) # 設置y刻度 fig.set_xticklabels("%.1f" %i for i in range(10)) # x軸刻度標籤 fig.set_yticklabels("%.2f" %i for i in [0,0.2,0.4,0.6,0.8,1.0,1.2]) # y軸刻度標籤函數
print(fig,type(fig))
![4.png](https://upload-images.jianshu.io/upload_images/2330091-2a380146238d0e50.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### 其餘元素可視性
複製代碼
x = np.linspace(-np.pi,np.pi,256,endpoint = True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s)
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x')
plt.tick_params(bottom='on',top='off',left='on',right='off')
import matplotlib matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'inout'
frame = plt.gca() #plt.axis('off')
#frame.axes.get_xaxis().set_visible(False) #frame.axes.get_yaxis().set_visible(False)
![5.png](https://upload-images.jianshu.io/upload_images/2330091-e57a97557b67e799.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
####【課程3.3】 圖表的樣式參數
    linestyle、style、color、marker
>##### linestyle參數
複製代碼
plt.plot([i**2 for i in range(100)], linestyle = '-.')
![6.png](https://upload-images.jianshu.io/upload_images/2330091-e3dfcd9220e0a0e9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### marker參數
複製代碼
s = pd.Series(np.random.randn(100).cumsum()) s.plot(linestyle = '--', marker = '.')
![7.png](https://upload-images.jianshu.io/upload_images/2330091-15c0e5e82532d4c7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### color參數
複製代碼
plt.hist(np.random.randn(100), color = 'g',alpha = 0.8)
df = pd.DataFrame(np.random.randn(1000, 4),columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.',alpha = 0.8,colormap = 'GnBu')
![8.png](https://upload-images.jianshu.io/upload_images/2330091-3ecd60c25321be36.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### style參數,能夠包含linestyle,marker,color
複製代碼
ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000)) ts.plot(style = '--g.',grid = True)
![9.png](https://upload-images.jianshu.io/upload_images/2330091-52b6af5af44a41c9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### 總體風格樣式
複製代碼
import matplotlib.style as psl print(plt.style.available)
psl.use('ggplot') ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000)) ts.plot(style = '--g.',grid = True,figsize=(10,6))
![10.png](https://upload-images.jianshu.io/upload_images/2330091-93f5897fb0213ef6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
####【課程3.4】 刻度、註解、圖表輸出
    主刻度、次刻度
>##### 刻度
複製代碼
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
t = np.arange(0.0, 100.0, 1) s = np.sin(0.1np.pit)np.exp(-t0.01) ax = plt.subplot(111) #注意:通常都在ax中設置,再也不plot中設置 plt.plot(t,s,'--*') plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both')
#plt.legend() # 圖例
xmajorLocator = MultipleLocator(10) # 將x主刻度標籤設置爲10的倍數 xmajorFormatter = FormatStrFormatter('%.0f') # 設置x軸標籤文本的格式 xminorLocator = MultipleLocator(5) # 將x軸次刻度標籤設置爲5的倍數
ymajorLocator = MultipleLocator(0.5) # 將y軸主刻度標籤設置爲0.5的倍數 ymajorFormatter = FormatStrFormatter('%.1f') # 設置y軸標籤文本的格式 yminorLocator = MultipleLocator(0.1) # 將此y軸次刻度標籤設置爲0.1的倍數
ax.xaxis.set_major_locator(xmajorLocator) # 設置x軸主刻度 ax.xaxis.set_major_formatter(xmajorFormatter) # 設置x軸標籤文本格式 ax.xaxis.set_minor_locator(xminorLocator) # 設置x軸次刻度
ax.yaxis.set_major_locator(ymajorLocator) # 設置y軸主刻度 ax.yaxis.set_major_formatter(ymajorFormatter) # 設置y軸標籤文本格式 ax.yaxis.set_minor_locator(yminorLocator) # 設置y軸次刻度
ax.xaxis.grid(True, which='both') #x座標軸的網格使用主刻度 ax.yaxis.grid(True, which='minor') #y座標軸的網格使用次刻度
#刪除座標軸的刻度顯示 #ax.yaxis.set_major_locator(plt.NullLocator()) #ax.xaxis.set_major_formatter(plt.NullFormatter())
![11.png](https://upload-images.jianshu.io/upload_images/2330091-5b683cb30548fbcf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### 註解
複製代碼
df = pd.DataFrame(np.random.randn(10,2)) df.plot(style = '--o') plt.text(5,0.5,'hahaha',fontsize=10)
![12.png](https://upload-images.jianshu.io/upload_images/2330091-ec7908d102b08eb4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>#####圖表輸出
複製代碼
df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.',alpha = 0.5) plt.legend(loc = 'upper left') plt.savefig('C:/Users/Hjx/Desktop/pic.png', dpi=400, bbox_inches = 'tight', facecolor = 'g', edgecolor = 'b')
![13.png](https://upload-images.jianshu.io/upload_images/2330091-5163f2d3ed71d5f7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
####【課程3.5】 子圖
    在matplotlib中,整個圖像爲一個Figure對象
在Figure對象中能夠包含一個或者多個Axes對象
每一個Axes(ax)對象都是一個擁有本身座標系統的繪圖區域
    plt.figure, plt.subplot
>##### plt.figure() 繪圖對象
複製代碼
fig1 = plt.figure(num=1,figsize=(4,2)) plt.plot(np.random.rand(50).cumsum(),'k--') fig2 = plt.figure(num=2,figsize=(4,2)) plt.plot(50-np.random.rand(50).cumsum(),'k--')
![14.png](https://upload-images.jianshu.io/upload_images/2330091-9cb8e76e6490833a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### 子圖建立1 - 先創建子圖而後填充圖表
複製代碼
fig = plt.figure(figsize=(10,6),facecolor = 'gray')
ax1 = fig.add_subplot(2,2,1) # 第一行的左圖 plt.plot(np.random.rand(50).cumsum(),'k--') plt.plot(np.random.randn(50).cumsum(),'b--')
ax2 = fig.add_subplot(2,2,2) # 第一行的右圖 ax2.hist(np.random.rand(50),alpha=0.5)
ax4 = fig.add_subplot(2,2,4) # 第二行的右圖 df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')
![15.png](https://upload-images.jianshu.io/upload_images/2330091-effd8c5af1a6ad84.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### 子圖建立2 - 建立一個新的figure,並返回一個subplot對象的numpy數組 → plt.subplot
複製代碼
fig,axes = plt.subplots(2,3,figsize=(10,4)) ts = pd.Series(np.random.randn(1000).cumsum()) print(axes, axes.shape, type(axes))
ax1 = axes[0,1] ax1.plot(ts)
![16.png](https://upload-images.jianshu.io/upload_images/2330091-0810c5bc9b8ea406.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>#####plt.subplots,參數調整
複製代碼
fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2): for j in range(2): axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5) plt.subplots_adjust(wspace=0,hspace=0)
![17.png](https://upload-images.jianshu.io/upload_images/2330091-5f21e64bebd8fa15.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
>##### 子圖建立3 - 多系列圖,分別繪製
複製代碼
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.',alpha = 0.4,grid = True,figsize = (8,8), subplots = True, layout = (2,3), sharex = False) plt.subplots_adjust(wspace=0,hspace=0.2)
![18.png](https://upload-images.jianshu.io/upload_images/2330091-970e573c768c2138.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<br>
#####最後:
[以上完整代碼](https://github.com/ChaoRenYuan/Python/tree/master/Python數據分析工具/圖表繪製工具:Matplotlib)
複製代碼