四、刻度、註解、圖表輸出

n [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
In [9]:
# 刻度

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()  # 圖例

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='majpr') #x座標軸的網格使用主刻度
# ax.yaxis.grid(True, which='minor') #y座標軸的網格使用次刻度
# which:格網顯示         minor   majpr(主)  both

#刪除座標軸的刻度顯示
#ax.yaxis.set_major_locator(plt.NullLocator()) 
# ax.xaxis.set_major_formatter(plt.NullFormatter()) 
 
In [25]:
# 註解

df = pd.DataFrame(np.random.randn(10,2))
df.plot(style = '--o')
plt.text(5,0.5,'hahaha',fontsize=10)  
# 註解 → 橫座標,縱座標,註解字符串
Out[25]:
Text(5,0.5,'hahaha')
 
In [36]:
# 圖表輸出

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.grid()
plt.savefig('./pic.png',
            dpi=400,
           #  bbox_inches = 'tight',
            facecolor = 'g',
            edgecolor = 'b')
# 可支持png,pdf,svg,ps,eps…等,之後綴名來指定
# dpi是分辨率
# bbox_inches:圖表須要保存的部分。若是設置爲‘tight’,則嘗試剪除圖表周圍的空白部分。
# facecolor,edgecolor: 圖像的背景色,默認爲‘w’(白色)
 
In [ ]:
相關文章
相關標籤/搜索