1.圖名,圖例,軸標簽,軸邊界,軸刻度,軸刻度標簽
# 圖名,圖例,軸標簽,軸邊界,軸刻度,軸刻度標簽等 df = pd.DataFrame(np.random.rand(10,2),columns=['A','B']) fig = df.plot(figsize=(6,4)) # figsize:創建圖表窗口,設置窗口大小 # 創建圖表對象,並賦值與fig plt.title('Interesting Graph - Check it out') # 圖名 plt.xlabel('Plot Number') # x軸標簽 plt.ylabel('Important var') # y軸標簽 plt.legend(loc = 'upper right') # 顯示圖例,loc表示位置 # 'best' : 0, (only implemented for axes legends)(自適應方式) # 'upper right' : 1, # 'upper left' : 2, # 'lower left' : 3, # 'lower right' : 4, # 'right' : 5, # 'center left' : 6, # 'center right' : 7, # 'lower center' : 8, # 'upper center' : 9, # 'center' : 10, 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軸刻度標簽 #保留小數點后2位小數
# 范圍只限定圖表的長度,刻度則是決定顯示的標尺 → 這里x軸范圍是0-12,但刻度只是0-9,刻度標簽使得其顯示1位小數 # 軸標簽則是顯示刻度的標簽 print(fig,type(fig)) # 查看表格本身的顯示方式,以及類別
輸出結果:
Axes(0.125,0.125;0.775x0.775) <class 'matplotlib.axes._subplots.AxesSubplot'>
2.
# 其他元素可視性 x = np.linspace(-np.pi,np.pi,256,endpoint = True) #linspace()通過指定開始值、終值和元素個數創建表示等差數列的一維數組,可以通過endpoint參數指定是否包含終值,默認值為True,即包含終值。 c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s) # 通過ndarry創建圖表 plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both') # 顯示網格 # linestyle:線型 # color:顏色 # linewidth:寬度 # axis:x,y,both,顯示x/y/兩者的格網 plt.tick_params(bottom='on',top='off',left='on',right='off') # 顯示刻度的那根軸線,凸出來的地方。設置為off時都不顯示。默認為全顯示 import matplotlib matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'inout' # 設置刻度的方向,in,out,inout 設置為in,刻度突出的部分在里面顯示,out在外面顯示,inout在中間顯示 # 這里需要導入matploltib,而不僅僅導入matplotlib.pyplot frame = plt.gca() #plt.axis('off') # 關閉坐標軸 #frame.axes.get_xaxis().set_visible(False) #frame.axes.get_yaxis().set_visible(False) # x/y 軸不可見
3.
# 注解 df = pd.DataFrame(np.random.randn(10,2)) print(df) df.plot(style = '--o') # plt.text(5,0.5,'hahaha',fontsize=10) # 注解 → 橫坐標,縱坐標,注解字符串 for i in range(10): plt.text(i,df[0].iloc[i],df[0].iloc[i],fontsize=10) #對0列的元素來說,標注y點的坐標。
輸出:
0 1 0 0.091094 -0.417407 1 0.770065 -1.215896 2 -1.279151 -0.512889 3 0.231089 0.768293 4 -1.874938 0.051870 5 -0.046272 -0.041660 6 0.473722 0.144373 7 -0.054020 1.756313 8 -1.437889 2.679062 9 -1.169249 -0.029428
4. 圖片保存
# 圖表輸出 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/Desktop/pdd.png', dpi=400, bbox_inches = 'tight', facecolor = 'g', edgecolor = 'b') # 可支持png,pdf,svg,ps,eps…等,以后綴名來指定 # dpi是分辨率 # bbox_inches:圖表需要保存的部分。如果設置為‘tight’,則嘗試剪除圖表周圍的空白部分。 # facecolor,edgecolor: 圖像的背景色,默認為‘w’(白色)