用Matplotlib畫水平柱狀圖和折線圖的個人使用心得與總結

從4月5號到18號研究了兩週的matplotlib,算是小有收穫。網上關於matplotlib的使用大大小小問題的回答並不是很全面比較零碎,有些還是得靠摸索。這段時間主要研究了水平柱狀圖和折線圖的使用,總結並記錄一下。

水平柱狀圖

# 導入繪圖包,分別導入避免出錯,儘量不用from pylab import *
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches

第一步,一定是定義一個畫布

# 繪圖窗口尺寸(6英寸,5英寸),分辨率120,背景顏色設置爲白色
plt.figure(figsize=(6,5),dpi=120,facecolor='white')
# 可顯示中文字,字體爲雅黑
plt.rcParams['font.sans-serif'] = ['SimHei']
# 刻度值可以顯示負數,避免顯示問題
plt.rcParams['axes.unicode_minus'] = False
# 可以調用各種風格,這個風格無邊框,不用額外設置,看着乾淨,用的比較多
# 可以使用plt.style.available獲取所有美化樣式,選擇一個合適的
plt.style.use('fivethirtyeight')

第二步,我自己把水平柱狀圖分爲單柱和多柱。

# 不管多少柱,保持x和y對應的值的數量相同
width = 0.1 # 設置柱狀圖的寬度
x1 = [1.1,2,3.1,4.6,5] # 5個值
# x2 = [0.85] # 1個值
y1 = [0,1,2,3,4] # 也要5個值
# y2 = [0] # 也要1個值
y_labels = ['xxx','xxx','xxx','xxx','xxx'] # 5個標籤對應5個值
idx = np.arange(len(x1))
# idx = np.arange(len(x2))

第三步,畫圖

# 可設置的參數很多,width,height,align,facecolor,edgecolor,alpha,label,zorder
# 通常align設置爲center不用去調idx值對齊;alpha可以調透明度,越小越透明;zorder表示層級
# zorder=2的圖像覆蓋到zorder=1之上
plt.barh(
        idx,x1,
        width,
        facecolor = 'blue',
        edgecolor = 'white',
        alpha = 0.3,
        zorder = 1,
        label = 'xxx')

第四步,設置輔助顯示層的一些參數

  1. title常用參數
    fontsize設置字體大小,默認12,可選參數 [‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’,’x-large’, ‘xx-large’]
    fontweight設置字體粗細,可選參數 [‘light’, ‘normal’, ‘medium’, ‘semibold’, ‘bold’, ‘heavy’, ‘black’]
    fontstyle設置字體類型,可選參數[ ‘normal’ | ‘italic’ | ‘oblique’ ],italic斜體,oblique傾斜
    verticalalignment設置水平對齊方式 ,可選參數 : ‘center’ , ‘top’ , ‘bottom’ ,’baseline’
    horizontalalignment設置垂直對齊方式,可選參數:left,right,center
    rotation(旋轉角度)可選參數爲:vertical,horizontal 也可以爲數字
    alpha透明度,參數值0至1之間
    backgroundcolor標題背景顏色
    bbox給標題增加外框 ,常用參數如下:
    boxstyle方框外形
    facecolor(簡寫fc)背景顏色
    edgecolor(簡寫ec)邊框線條顏色
    edgewidth邊框線條大小
  2. xlabel,ylabel參數
    fontsize:字體大小自調,默認12
    verticalalignment:’top’, ‘bottom’, ‘center’, ‘baseline’
    horizontalalignment:’center’, ‘right’, ‘left’
    rotation: ‘vertical’,’horizontal’,’vertical’
  3. subplots_adjust參數
    如果y軸或x軸刻度標籤放不進一個畫面裏,show圖片後可以通過configure subplots按鈕進行調整,再把其參數輸入到代碼中
  4. legend圖例參數
    loc參數,
    0: ‘best’
    1: ‘upper right’
    2: ‘upper left’
    3: ‘lower left’
    4: ‘lower right’
    5: ‘right’
    6: ‘center left’
    7: ‘center right’
    8: ‘lower center’
    9: ‘upper center’
    10: ‘center’
    fontsize參數
    fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
    frameon,edgecolor,facecolor參數
    plt.legend(loc=’best’,frameon=False) #去掉圖例邊框
    plt.legend(loc=’best’,edgecolor=’blue’) #設置圖例邊框顏色
    plt.legend(loc=’best’,facecolor=’blue’) #設置圖例背景顏色,若無邊框,參數無效
plt.title('xxx',fontsize=14,bbox=dict(facecolor='green',edgecolor='blue',alpha=0.6))
plt.xlabel('xxx',fontsize=10)
plt.ylabel('xxx',fontsize=10)
plt.subplots_adjust(left=0.1,right=0.9,top=0.9,bottom=0.2,hspace=0.12,wspace=0.1)
plt.legend(loc='best',fontsize=10)
# 表示不顯示座標軸
plt.axis('off')

第五步,設置一些座標軸,刻度,刻度標籤,矩形的參數

ax = plt.gca() # 獲取當前axes
# spines是連接軸刻度標記的線,將其顏色設爲none就是去掉該線
ax.spines['bottom'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['left'].set_color('grey')
ax.spines['left'].set_linewidth(1)
# 可以設置爲x軸不顯示/y軸不顯示
ax.axes.get_xaxis().set_visible(False)
# x軸範圍
ax.set_xlim(-1, 1.1)
# x軸座標刻度(可以表示成具體的幾個值)
ax.set_xticks([-1, 0, 1])
# x軸刻度標籤,方便調大小
ax.set_xticklabels(['-1', '0', '1'], fontsize=10)
# y軸範圍
ax.set_ylim(-0.2, len(y1)-0.2)
# y軸座標刻度(具體表示成幾個值,比如說0,1,2,3,4)
ax.set_yticks([0])
# y軸刻度標籤賦到座標刻度上
ax.set_yticklabels(['xxx'],fontsize=10)
# 畫矩形框(別忘了在開頭導入patches)
# 前兩個參數是相對於(0,0)矩形的左下角座標,0.4是矩形的寬度,0.3是矩形的高度
# 矩形四個點座標(0.8,-0.15),(1.2,-0.15),(1.2,0.15),(0.8,0.15)
rect = patches.Rectangle((0.8,-0.15),0.4,0.3,linewidth=0.8,edgecolor='black',facecolor='none',zorder=3)
ax.add_patch(rect)

第六步,有些時候需要引入數據標籤

前邊設置的x1、y1值其實就代表了不同柱子在圖形中的位置(座標),通過for循環找到每一個x1、y1值的相應座標——a、b,再使用plt.text在對應位置添文字說明來生成相應的數字標籤,而for循環也保證了每一個柱子都有標籤。
其中,a-0.03, b表示在每一柱子對應x值左側0.03處、y值標註文字說明 ,ha=’center’, va= ‘bottom’代表horizontalalignment(水平對齊)、verticalalignment(垂直對齊)的方式,fontsize則是文字大小。
數字標籤

for a,b in zip(x1,y1):
    plt.text(a-0.03,b,a,ha='right',va='center',fontsize=14)

第七步,網格設置,保存圖像,展示圖像

# 背景中的網格,False爲取消網格,True爲顯示網格
plt.grid(False)
# savefig一定要在show之前,要不然就是空白圖像,路徑設置注意要用兩個斜槓'\\'
plt.savefig('D:\\test\\graph.png')
# 展示圖像
plt.show()

PS:總結一下畫子圖

如果是分成上下兩個規則的子圖
plt.subplot(211)
定義圖像,輔助顯示參數等
plt.subplot(212)
定義圖像,輔助顯示參數等

如果是不規則劃分子圖,類似這樣的
這裏寫圖片描述
將整個表按照 2*2 劃分
前兩個簡單, 分別是 (2, 2, 1) 和 (2, 2, 2)
但是第三個圖呢, 他佔用了 (2, 2, 3) 和 (2, 2, 4)
顯示需要對其重新劃分, 按照 2 * 1 劃分
前兩個圖佔用了 (2, 1, 1) 的位置
因此第三個圖佔用了 (2, 1, 2) 的位置
這裏寫圖片描述

折線圖
思路和柱狀圖差不多
第一步,定義畫布
第二步,折線圖的值的設置

x = [0,1,2,3,4,5] # 6個值
# 兩條折線
y1 = [2.3,2,3,2.3,1.7,3] # 對應也要6個值
y2 = [2,1.7,2.7,2,2,2.3] # 對應也要6個值
x_labels = ['xxx','xxx','xxx','xxx','xxx','xxx']

第三步,畫圖
折線圖用plt.plot直接畫
linestyle參數:
-, solid(實線)
–, dashed (虛線)
-., dashdot
:, dotted
”, ’ ‘, None
linewidth參數(設置線條粗細)
marker參數
‘.’: point marker
‘,’: pixel marker
‘o’: circle marker
‘v’: triangle_down marker
‘^’: triangle_up marker
‘<’: triangle_left marker
‘>’: triangle_right marker
‘1’: tri_down marker
‘2’: tri_up marker
‘3’: tri_left marker
‘4’: tri_right marker
‘s’: square marker
‘p’: pentagon marker
‘*’: star marker
‘h’: hexagon1 marker
‘H’: hexagon2 marker
‘+’: plus marker
‘x’: x marker
‘D’: diamond marker
‘d’: thin_diamond marker
‘|’: vline marker
‘_’: hline marker

以下關鍵字參數可以用來設置marker的樣式:
marker
markeredgecolor 或 mec
markeredgewidth 或 mew
markerfacecolor 或 mfc
markerfacecoloralt 或 mfcalt
markersize 或 ms

設置空心圓標記的方法:mfc設置爲none,mec設置爲一個顏色,mew設置的寬一些,比較好看

plt.plot(x,y1,linestyle='-',marker='o',markersize=8,markerfacecolor='none',markeredgecolor='deepskyblue',markeredgewidth=1.5,linewidth =2,color='deepskyblue',label="xxx")
plt.plot(x,y2,linestyle='--',marker='o',markersize=8,markerfacecolor='none',markeredgecolor='darkorange',markeredgewidth=1.5,linewidth =2,color='darkorange',label="xxx")

第四步,設置輔助顯示層的一些參數(和柱狀圖一樣)
plt.title
plt.xlabel / pt.ylabel
plt.subplots_adjust
plt.legend

第五步,設置一些座標軸,刻度,刻度標籤,矩形的參數

ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['bottom'].set_color('black')
ax.spines['bottom'].set_linewidth(2)
ax.set_xlim(-0.5,len(x)-0.5)
ax.set_xticks(x)
ax.set_xticklabels(x_labels,fontsize=7)

PS: 如果想把x軸座標刻度(0,1,2,3,4)對應成刻度標籤(’xxx’,’xxx’,’xxx’,’xxx’,’xxx’)
兩種方法:
第一種,
plt.xticks(x,x_labels,fontsize=7)
第二種,
ax = plt.gca()
ax.set_xticks(x)
ax.set_xticklabels(x_labels,fontsize=7)

第六步,數據標籤

for a,b in zip(x,y1):
    plt.text(a,b,b,ha='right',va='bottom',fontsize=14)
for a,b in zip(x,y2):
    plt.text(a,b,b,ha='right',va='bottom',fontsize=14)

第七步,網格設置,保存圖像,展示圖像

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