1. 共享坐標軸
當你通過pyplot.subplot()
、pyplot.axes()
函數或者Figure.add_subplot()
、Figure.add_axes()
方法創建一個Axes
時,你可以通過sharex
關鍵字參數傳入另一個Axes
表示共享X軸;或者通過sharey
關鍵字參數傳入另一個Axes
表示共享Y軸。共享軸線時,當你縮放某個Axes
時,另一個Axes
也跟着縮放。
舉例:
import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(211) ax1.plot([1,2,3,4,5]) ax2 = fig.add_subplot(212,sharex=ax1) ax2.plot([7,6,5,4,3,2,1]) fig.show()
2. 創建多個 subplot
如果你想創建網格中的許多subplot
,舊式風格的代碼非常繁瑣:
# 舊式風格 fig=plt.figure() ax1=fig.add_subplot(221) ax2=fig.add_subplot(222,sharex=ax1,sharey=ax1) ax3=fig.add_subplot(223,sharex=ax1,sharey=ax1) ax4=fig.add_subplot(224,sharex=ax1,sharey=ax1)
新式風格的代碼直接利用pyplot.subplots()
函數一次性創建:
# 新式風格的代碼 fig,((ax1,ax2),(ax3,ax4))=plt.subplots(2,2,sharex=True,sharey=True) ax1.plot(...) ax2.plot(...) ...
它創建了Figure
和對應所有網格SubPlot
。你也可以不去解包而直接:
# 新式風格的代碼 fig,axs=plt.subplots(2,2,sharex=True,sharey=True) ax1=axs[0,0] ax2=axs[0,1] ax3=axs[1,0] ax4=axs[1,1] ...
返回的axs
是一個nrows*ncols
的array
,支持numpy
的索引。
3. 調整橫坐標不重疊
未調整前:
import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates d0 = datetime.date(2016,1,1) ndates = [d0+datetime.timedelta(i) for i in range(10)] n_ys = [i*i for i in range(10)] fig,ax = plt.subplots(1) ax.plot(ndates,n_ys)
(1)matplotlib.dates.DateFormatter
當x
軸為時間日期時,有可能間隔太密集導致顯示都疊加在一起。此時可以用matplotlib.figure.Figure.autofmt_xdate()
函數來自動調整X軸日期的顯式。
也可以調整X軸的顯示格式。當X軸為時間時,其顯示由Axes.fmt_xdata
屬性來提供。該屬性是一個函數對象或者函數,接受一個日期參數,返回該日期的顯示字符串。matplotlib
已經提供了許多date formatter
,你可以直接使用ax.fmt_xdata=matplotlib.dates.DateFormatter('%Y-%m-%d')。
fig2,ax2 = plt.subplots(1) ax2.plot(ndates,n_ys) fig2.autofmt_xdate() # 調整x軸時間的顯示 ax2.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') # 格式化器 plt.show()
(2)plt.xticks(rotation=順時針旋轉角度)
fig3,ax3 = plt.subplots(1) ax3.plot(ndates,n_ys) plt.xticks(rotation=25) plt.tight_layout() plt.show()
(3)ax.set_xticklabels(rotation=順時針旋轉角度)
fig4,ax4 = plt.subplots(1) ax4.plot(ndates,n_ys) ax4.set_xticklabels(ndates,rotation=25,ha="right") plt.tight_layout() plt.show()
4. 放置 text box
當你在Axes
中放置text box
時,你最好將它放置在axes coordinates
下,這樣當你調整X軸或者Y軸時,它能夠自動調整位置。
你也可以使用Text
的.bbox
屬性來讓這個Text
始終放在某個Patch
中。其中.bbox
是個字典,它存放的是該Patch
實例的屬性。
語法:
ax.text(x, y, s, fontdict=None, withdash=False, **kwargs)
功能:將文本s添加到數據坐標中位置x,y的軸上。
參數:
- x,y:張量,放置文本的位置。 默認情況下,這是在數據坐標中。 可以使用變換參數來更改坐標系。
- s:文本
- fontdict:字典,可選,覆蓋默認文本屬性的字典。 如果fontdict為None,則默認值由rc參數確定。
- withdash:布爾值,可選,默認值:False。創建一個〜matplotlib.text.TextWithDash實例,而不是一個〜matplotlib.text.Text實例。
horizontalalignment
,
verticalalignment
和
multialignment
來布置文本。
horizontalalignment
控制文本的x
位置參數表示文本邊界框的左邊,中間或右邊。verticalalignment
控制文本的y
位置參數表示文本邊界框的底部,中心或頂部。multialignment
,僅對於換行符分隔的字符串,控制不同的行是左,中還是右對齊。
text()
命令顯示各種對齊方式的例子。 在整個代碼中使用
transform = ax.transAxes
,表示坐標相對於軸邊界框給出,其中
0,0
是軸的左下角,
1,1
是右上角。
舉例:
import matplotlib.pyplot as plt import numpy as np fig,ax = plt.subplots(1) x = 30 * np.random.randn(10000) mu = x.mean() median = np.median(x) sigma = x.std() textstr = '$\mu=%.2f$ \n $\mathrm{median}=%.2f$ \n $\sigma=%.2f$'%(mu,median,sigma) ax.hist(x,50) props=dict(boxstyle='round',facecolor='wheat',alpha=0.5) ax.text(0.05,0.95,textstr,transform=ax.transAxes,fontsize=14,verticalalignment='top',bbox=props) fig.show()
5. LATEX文字
要想在文本中使用LATEX,你需要使用'$...$'這種字符串(即使用'$'作為界定符)。通常建議使用raw字符串,即r'$...$'的格式,因為原生字符串不會轉義'\',從而使得大量的LATEX詞法能夠正確解析。
舉例:
sns.set(style='ticks') sns.set_context(rc={'lines.linewidth':5}) plt.xlim((10,100.5)) plt.ylim((0,41)) plt.xticks(np.arange(10, 100.5, 15)) plt.yticks(np.arange(0,41,10)) # "greyish", "faded green", colors = ["windows blue", "dark green", "slate grey"] palette = sns.xkcd_palette(colors) ax = sns.lineplot(x="phi", y="MAPE",hue = 'alg', style='alg',data=df_mape_change_phi, markers = False,palette=palette) # - 實線-- 短線-.短點相間線:虛點線 # ax.lines[0].set_linestyle("-") # ax.lines[1].set_linestyle("-.") # ax.lines[2].set_linestyle("--") plt.xlabel(r'$\varphi$', fontdict={'color': 'black','family': 'Times New Roman','size': 18}) plt.ylabel(r'MAPE($\times 10^{-3}$)', fontdict={'color': 'black','family': 'Times New Roman','size': 18}) plt.legend(['IMTEC','ER','SRD'],prop={'style': 'italic'},handlelength=4)#圖例 plt.grid(True) plt.tight_layout() plt.savefig('local_pic/phi_mape.jpg',dpi=600) # plt.savefig('loc_svg/TD_precision_tasknum.svg') plt.show()
6. 平移坐標軸
Axes.spines
是個字典,它存放了四個鍵,分別為:
Axes.spines['left'],
Axes.spines['right'],
Axes.spines['top'],
Axes.spines['bottom']
他們都是一個matplotlib.spines.Spine
對象,該對象繼承自matplotlib.patches.Patch
對象,主要是設置圖形邊界的邊框。
-
Spine.set_color('none')
:不顯示這條邊線 -
Spine.set_position((position))
:將邊線移動到指定坐標,其中position
是一個二元元組,指定了(position type,amount)
,position type
可以是:outward
:在繪圖區域之外放置邊線,離開繪圖區域的距離由amount
指定(負值則在會去區域內繪制)axes
:在Axes coordinate
內放置邊線(從 0.0 到 1.0 )data
:在data coordinate
內放置邊線
你也可以指定
position
為:'center'
,等價於('axes',0.5)
;或者'zero'
,等價於('data',0.0)
舉例:
import matplotlib.pyplot as plt import numpy as np X = np.linspace(-2,2,num=100) Y = np.sin(X) fig = plt.figure(figsize=(8,4)) # ax1 ax1 = fig.add_subplot(1,2,1) ax1.plot(X,Y) ax1.set_title('default') # ax2 ax2 = fig.add_subplot(1,2,2) ax2.plot(X,Y) ax2.spines['right'].set_color('none') # 不顯示右邊框 ax2.spines['top'].set_color('none') # 不顯示上邊框 ax2.xaxis.set_ticks_position('bottom') # 設置x坐標軸為下邊框 ax2.yaxis.set_ticks_position('left') # 設置y坐標軸為左邊框 ax2.spines['bottom'].set_position(('data',0))# 設置x軸, y軸在(0, 0)的位置 ax2.spines['left'].set_position(('data',0)) ax2.set_title('move axis')
7. 清除繪圖
(1)通過pyplot清除繪圖
pyplot.cla()
:清除current axis
。非當前axis
不受影響pyplot.clf()
:清除current figure
。但是它不關閉window
pyplot.close()
:關閉window
(2)通過面向對象的方法
Figure.clf()
:清除該Figure
對象的所有內容。
8. 清除X坐標和Y坐標
Axes.set_xticks(()) Axes.set_yticks(()) Axes.set_axis_off() #清除tick和邊框
9. 設置中文
在linux
下,為了支持中文,則在開頭設置:
import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] #matplotlib 中文字體
參考文獻:
【1】matplotlib的基本用法(三)——調整坐標軸_SnailTyan-CSDN博客
【2】huaxiaozhuan大佬博客