Python數據分析實戰【第三章】3.4-Matplotlib 刻度、註解、圖表輸出【python】

【課程3.4】 刻度、註解、圖表輸出

主刻度、次刻度

1.刻度

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

t = np.arange(0.0, 100.0, 1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)
ax = plt.subplot(111) #注意:一般都在ax中設置,不再plot中設置
plt.plot(t,s,'--*')
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both')  
# 網格
#plt.legend()  # 圖例

#1.定義參數
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的倍數
  
#2.傳遞參數
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座標軸的網格使用次刻度
# which:格網顯示

#刪除座標軸的刻度顯示
#ax.yaxis.set_major_locator(plt.NullLocator()) 
#ax.xaxis.set_major_formatter(plt.NullFormatter()) 

在這裏插入圖片描述

2.註解


df = pd.DataFrame(np.random.randn(10,2))
df.plot(style = '--o')
plt.text(5,0.5,'hahaha',fontsize=10)  
# 註解 → 橫座標,縱座標,註解字符串

在這裏插入圖片描述

3.圖表輸出


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')
# 可支持png,pdf,svg,ps,eps…等,以後綴名來指定
# dpi是分辨率
# bbox_inches:圖表需要保存的部分。如果設置爲‘tight’,則嘗試剪除圖表周圍的空白部分。
# facecolor,edgecolor: 圖像的背景色,默認爲‘w’(白色)

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章