matplotlib可視化《2》圖形設置與調整


•figure和subplot

matplotlib的圖像都是位於figure對象中的,我們可以通過plt.figure創建一個新的figure:

1 fig=plt.figure(figsize=(6,6))#figsize控制畫布的大小

但figure是不能繪圖的,我們需要用fig.add_subplot的方式創建一個或者多個subplot才行:

ax1=fig.add_subplot(211)#表示選中2行1列的第一個畫布
x=np.linspace(0,8,num=50)
y1=np.sin(x)
ax1.plot(x,y1)
1 ax2=fig.add_subplot(212)#第二塊畫布
2 x=np.linspace(0,8,num=50)
3 y2=np.cos(x)
4 ax2.plot(x,y2)
5 fig

 

 

 

 

plt.subplots

plt.subplots是更為簡單的方法,可以直接創建多個畫布,直接調用即可

1 fig,axes=plt.subplots(2,1,sharex=True,figsize=(7,7))
1 axes#為數組,所以我們可以用數值索引的方式調用
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7f97c0ba9350>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7f97ef1eb090>],
      dtype=object)
1 axes[0].plot(x,y1)#第一塊畫布
2 axes[1].plot(x,y2)#第二塊畫布
3 fig

 

 

 

~plt.subplots_adjust

plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None

參數含義:
left, right, bottom, top:子圖所在區域的邊界。
當值大於1.0的時候子圖會超出figure的邊界從而顯示不全;值不大於1.0的時候,子圖會自動分布在一個矩形區域(下圖灰色部分)。
要保證left < right, bottom < top,否則會報錯。
如下圖:

 

wspace, hspace:子圖之間的橫向間距、縱向間距分別與子圖平均寬度、平均高度的比值。

 

舉個例子

1 fig,axes=plt.subplots(2,2,facecolor="darkseagreen",figsize=(6,6))
2 plt.subplots_adjust(left=0.1, wspace=0.1, top=0.9,hspace=0.2) #位置調整

 

 

•美圖

~顏色、標記和線型

1 fig,axes=plt.subplots(2,2,facecolor="darkseagreen",figsize=(6,6))
2 plt.subplots_adjust(left=0.1, wspace=0.1, top=0.9,hspace=0.2) #位置調整
3 axes[0,0].plot(np.random.randn(20).cumsum(),"ro--")#“ro--”簡單表
4 axes[0,1].plot(np.random.randn(20).cumsum(),color="g",linestyle="dashed",marker="o")#展開
5 fig

 

 

顏色和線型參考表如下

 

~標題、刻度、標簽和圖例

標題

 

1 #整個figure的標題
2 fig.suptitle('我的畫板', fontsize=16, fontweight='bold')
3 #各個畫布的標題
4 axes[0,0].set_title("畫板一")
5 axes[0,1].set_title("畫板二")
6 axes[1,0].set_title("畫板三")
7 axes[1,1].set_title("畫板四")
8 fig

 

 

刻度、標簽

1 axes[1,0].plot(x,y1)
2 axes[1,0].set_xticks([0,2,4,6,8])#設置刻度
3 axes[1,0].set_xticklabels(["第一級","第二級","第三級","第四級","第五級"])#給刻度命名
4 axes[1,0].set_xlabel("x的值")#標簽名
5 fig

 

 

 

圖例

 

 1 plt.style.use('ggplot')#設置背景
 2 x=np.linspace(0,8,num=50)
 3 y1=np.sin(x)
 4 y2=np.cos(x)
 5 plt.plot(x,y1,"k-",label="sin函數")
 6 plt.plot(x,y2,"go--",label="cos函數")
 7 plt.title("sin-cos圖")
 8 plt.ylabel("y軸")
 9 plt.xlabel("x軸")
10 plt.legend()#作圖時加label,這里才會生成legend

 

• 注釋

~text

1 tb=test.groupby(["所屬區域"]).agg({"數量":np.mean,})#根據實際需求對一表格畫柱狀圖,先分類匯總 2 tb

 

 

1 fig = plt.figure(figsize=(7, 5),  dpi=90)  # 聲明畫布1
2 ax = fig.add_subplot(1,1,1) #  聲明繪圖區
3 x, y = tb.index, list(tb["數量"])
4 plt.bar(x, y, color='dodgerblue', width=0.35, label='label1')
5 plt.grid(linestyle="-.", axis='y', alpha=0.4)#設置橫向網格
6 plt.tight_layout()
7 for a,b in zip(x,y):
8     plt.text(a, b,'%.3f'%b, ha = 'center',va = 'bottom',fontsize=10)

 

 

 

 注:plt.text在對應位置添文字說明來生成相應的數字標簽,a、b表示文字顯示在坐標軸的位置,'%.3f' % b,代表標注的文字,即每個柱子對應的y值, ha='center', va= 'bottom'代表horizontalalignment(水平對齊)、verticalalignment(垂直對齊)的方式,fontsize則是文字大小。

 

折線圖

tt=test.groupby(test["訂購日期"]).agg({"數量":np.sum})
x,y=tt.index,tt["數量"]
plt.plot(x,y,"go--")
for a,b in zip(x,y):
    plt.text(a,b,"%.3f"%b,ha="center",va="bottom")

 

 

~annotate

參數說明:

Axes.annotate(s, xy, *args, **kwargs)

  • s:注釋文本的內容
  • xy:被注釋的坐標點,二維元組形如(x,y)
  • xytext:注釋文本的坐標點,也是二維元組,默認與xy相同
  • arrowprops箭頭的樣式,dict(字典)型數據,如果該屬性非空,則會在注釋文本和被注釋點之間畫一個箭頭。可設置arrowstyle' 關鍵字

 

 

 1 fig, ax = plt.subplots()
 2  
 3 # 繪制一個余弦曲線
 4 t = np.arange(0.0, 4.0, 0.01)
 5 s = np.cos(2*np.pi*t)
 6 line, = ax.plot(t, s, lw=2)
 7  
 8 # 繪制一個綠色簡單的箭頭
 9 ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
10             xycoords='data',
11             arrowprops=dict(arrowstyle='simple',facecolor='green')
12             )
13 ax.set_ylim(-2, 2)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM