天天看點

matplotlib繪圖的基本設定基本圖-折線圖為例子圖1 畫布建立2 坐标軸、标題設定3 圖例4 添加注釋、數字标簽5 子圖6 其它設定

基本圖-折線圖為例

以折線圖為例,加上常見的一些圖表的設定

import matplotlib.pyplot as plt

# 中文字型顯示,隻要是中文就在前面加u
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong']
mpl.rcParams['axes.unicode_minus'] = False

# 資料源
x = [u'1月',u'2月',u'3月',u'4月',u'5月',u'6月',u'7月',u'8月',u'9月',u'10月',u'11月',u'12月']
y1 = [20,17,24,36,49,53,64,69,50,38,20,16]
y2 = [24,27,25,30,45,43,54,60,57,43,27,26]

# 建立畫布,設定畫布大小
plt.figure(figsize=(7,4))
plt.plot(x,y1,label=u'冰紅茶')  # 畫圖
plt.plot(x, y2, label=u'冰咖啡')
plt.title(u'2020年冷飲銷量',fontsize=14)  # 标題,字号設定
plt.xlabel(u'月份',loc='right')  # 位置設定
plt.ylabel(u'銷量(千杯)',rotation='horizontal',y=1,x=0)  # 方向,位置設定
plt.legend(bbox_to_anchor=(0.2,0.8))  # 加上圖例,設定位置
# 加資料注釋
for y in [y1,y2]:
    for i,v in enumerate(y):
        plt.annotate(v, (i,v+0.7))
# 加文字注釋
plt.plot(x,[75]*12,color='blue',linewidth=0.7,alpha=0.7)
plt.annotate(u'冰紅茶曆史最高',(10,75.7))
plt.plot(x,[64]*12,color='orange',linewidth=0.7,alpha=0.7)
plt.annotate(u'冰咖啡曆史最高',(10,64.7))

plt.show()  # 也可以不加,依然顯示
           
matplotlib繪圖的基本設定基本圖-折線圖為例子圖1 畫布建立2 坐标軸、标題設定3 圖例4 添加注釋、數字标簽5 子圖6 其它設定

子圖

# 資料源
x = [u'1月',u'2月',u'3月',u'4月',u'5月',u'6月',u'7月',u'8月',u'9月',u'10月',u'11月',u'12月']
y1 = [20,17,24,36,49,53,64,69,50,38,20,16]
y2 = [24,27,25,30,45,43,54,60,57,43,27,26]
x2 = [u'山東',u'河南',u'浙江',u'湖北',u'安徽']
y3 = [100,176,235,250,156]

fig,axes = plt.subplots(1,2,figsize=(10,4))
# axes[0]的主坐标軸
a1 = axes[0].plot(x,y1,label=u'冰紅茶',color='red',alpha=0.8)
a2 = axes[0].plot(x, y2, label=u'冰咖啡',color='#663300')
axes[0].set_title(u'2020冷飲銷量')
axes[0].set_xlabel(u'月份', loc='right')
axes[0].set_ylabel(u'銷量\n(千杯)', rotation='horizontal',y=1)
axes[0].set_ylim([0,80])
# axes[0]添加次坐标軸
ax2 = axes[0].twinx()
a3 = ax2.bar(x, [i+j for i,j in zip(y1,y2)], color='navy',alpha=0.5, label=u'總銷量')
ax2.set_ylabel(u'銷量\n(千杯)', rotation='horizontal',y=1.1)
ax2.set_ylim([0,170])
fig.legend(bbox_to_anchor=(0.45,0.87))  # 為整個圖添加圖例,這樣可以将axes[0]的兩個軸的圖例合并到一起
# axes[1]
axes[1].bar(x2, y3)
axes[1].set_title(u'2020冷飲分地區總銷量')
axes[1].set_xlabel(u'地區', loc='right')
axes[1].set_ylabel(u'銷量\n(千杯)', rotation='horizontal',y=1)
# 加資料标注
for i,v in enumerate(y3):
    axes[1].annotate(v, (i-0.2,v+0.7))
# 整個圖形的标題
plt.figtext(0.4,1,s=u'2020冷飲銷售狀況',fontsize=17)
# 子圖間距調整
plt.subplots_adjust(wspace=0.35)  # 讓兩個子圖之間的距離變大些,軸名稱不要重疊
plt.savefig(r'C:\Users\aa\Desktop\a.png',dpi=300, bbox_inches='tight')
           
matplotlib繪圖的基本設定基本圖-折線圖為例子圖1 畫布建立2 坐标軸、标題設定3 圖例4 添加注釋、數字标簽5 子圖6 其它設定

1 畫布建立

fig = plt.figure(
	num=None, 			圖像編号或名稱,數字為編号 ,字元串為名稱
	figsize=(6.4,4.8), 		指定figure的寬和高,機關為英寸;
	dpi=100, 			參數指定繪圖對象的分辨率,即每英寸多少個像素
	facecolor='white', 	背景顔色
	edgecolor='white', 	邊框顔色
	frameon=True,		是否顯示邊框
	tight_layout=False  是否是緊湊布局
)
           

2 坐标軸、标題設定

1 軸刻度範圍
plt.xlim():獲得坐标軸範圍,針對目前、最新建立的圖
plt.xlim([n,m]) plt.xlim(n,m) :設定坐标軸範圍,針對目前、最新建立的圖
plt.axis([0, 1100, 0, 1100000]):x和y坐标軸的最小值和最大值

2 軸刻度數與對應标簽
plt.xticks([v1,v2,...], ('G1', 'G2', ..), rotation=30,fontsize=15):先設定标簽位置再設定對應标簽,如果沒有标簽僅顯示刻度,如果有标簽就不顯示刻度。
plt.tick_params(axis='both', labelcolor='', labelsize=,width=):設定兩個軸上刻度标記的大小、顔色

3 軸标簽
plt.xlabel(' ', fontsize=14, loc={'center'},x=,y=,rotation= {'vertical'}) 
loc可選{'right'/'left'}
rotation可選 {'vertical', 'horizontal'}
x,y是标簽的位置,不能和loc一同使用

plt.ylabel(' ', fontsize=14, loc='center',rotation= {'vertical'},x=,y=) 
loc可選{'bottom','top'}

4 隐藏坐标軸
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

【标題】
plt.title(' ', fontsize=24)
           

3 圖例

1 加入圖例
plt.legend():針對目前、最新建立的圖,畫圖時要指明名稱,即label參數:plt.plot(x,y,label='')

2 參數
plt.legend(loc='', ncol=, bbox_to_anchor=(x,y),frameon=True)
loc的參數如下:
	best	upper right		upper left		lower left		lower right
	right	center left		center right	lower center	upper center
	center
ncol:設定列數
bbox_to_anchor:圖例相對于整個圖的位置(x,y),(0,0)表示整個圖的左下角,(1,1)為整個圖的右上角
frameon:是否顯示圖例的邊框,預設為True
其它邊框的樣式參數:
fancybox=True是否設定成圓角邊框
edgecolor='black'邊框的顔色
framealpha=1邊框的透明度,1是完全不透明
borderpad=1内邊距大小
shadow=True開啟陰影
fontsize=8/'small,x-small,large,medium..'
labelcolor='red'标簽文字的顔色
title圖例的标題
title_fontsize圖例的大小,同fontsize的設定

3 獲得位置
box = ax.get_position()

4 選擇圖例顯示的項
方法1:不想加的項不設定label
plt.plot(,,label='label1')
plt.plot()
plt.legend()

方法2:畫圖設定圖像執行個體
lines = plt.plot(x,y[:,:3]) #一次畫多條線
plt.legend(lines[:2], ['first','second'])

           
x = np.linspace(0,10,100)
plt.figure(figsize=(5,4))
plt.plot(x, np.sin(x), label='sine')
plt.plot(x, np.cos(x), label='cosine')
plt.ylim([-2,2])
plt.legend(loc='upper right',frameon=True,
           fancybox=True, edgecolor='black',framealpha=0.8, borderpad=1,shadow=True,
          labelcolor=['blue','orange'],title='三角函數',title_fontsize='large')
           
matplotlib繪圖的基本設定基本圖-折線圖為例子圖1 畫布建立2 坐标軸、标題設定3 圖例4 添加注釋、數字标簽5 子圖6 其它設定

圖例顯示不同尺寸的點

data:
 記錄數	地震區域	深度(公裡)	緯度	經度	震級
0	1	新疆		10		39.40	75.20	5.1
1	1	新疆		5		39.59	74.82	3.0
2	1	雲南省		10		24.72	97.92	4.6
3	1	雲南省		10		24.72	97.91	4.8
4	1	雲南省		10		24.72	97.92	3.4
plt.scatter(data['經度'],data['緯度'],c=data['震級'],s=data['深度(公裡)'],cmap='viridis',
            alpha=0.6,linewidth=0)
plt.colorbar(label='震級')
plt.clim(3,7)

# 建立深度的圖例
for deep in [10,100,200,500]:
    plt.scatter([], [], s=deep, alpha=0.6, label='{}公裡'.format(deep))
plt.legend(bbox_to_anchor=(1.5,0.55),labelspacing=1.5,title='深度', frameon=False,scatterpoints=1)
plt.title('我國地震震級及深度示意圖')
plt.xlabel('經度')
plt.ylabel('緯度')
           
matplotlib繪圖的基本設定基本圖-折線圖為例子圖1 畫布建立2 坐标軸、标題設定3 圖例4 添加注釋、數字标簽5 子圖6 其它設定

4 添加注釋、數字标簽

方法一:

plt.annotate(
text,		注釋文字
(x,y),			待注釋位置
xytext,		注釋的位置
xycoords,	待注釋位置的性質,可選項
arrowprops= 箭頭屬性設定:顔色,箭頭寬度,箭頭長度
	dict(facecolor='',headwidth=,headlength=)
horizontalalignment='left', 水準對齊
verticalalignment=''   垂直對齊
)

xycoords可選項:
'figure points' 'figure pixels' 'figure fraction'   距離圖層左下角的點、像素、百分比
'axes points'   'axes pixels'	'axes fraction' 	距離軸坐标左下角的點、像素、百分比
'data'  使用實際的軸坐标的資料(預設)
'polar' 使用極坐标系來處理,(弧度,長度)

最簡形式:
plt.annotate(text,(x,y)):xy處有注釋text
           

方法二:

plt.text(x, y, s, fontsize, bbox=dict(facecolor='red', alpha=0.5), va='bottom')
x, y注釋位置
s:注釋
bbox:注釋屬性設定
           

方法三:

p = [51,39]
fig,axes = plt.subplots(1,2,figsize=(6,4))
# text
p = [51,39]
fig,axes = plt.subplots(1,2,figsize=(6,4))
axes[0].bar([0,1],p,color=['grey','teal'],width=0.5)
axes[0].set_xticks([0,1])
axes[0].set_xticklabels(['January', 'February'])
for i,x in enumerate(p):
    axes[0].text(i,x+0.5, x) 
 
 # annotate    
axes[1].bar([0,1],p)
plt.xticks(range(len(p)), ['January', 'February'])
for i,x in enumerate(p):
    plt.annotate(x, (i,x+0.5))

# 當資料源獲得較為困難時,指派給圖,獲得其x,y
# a = axes[0].bar([0,1],p,color=['grey','teal'],width=0.5)
# for rect in a:
#     x = rect.get_x(),
#     y = rect.get_height()
#     axes[0].text(x + rect.get_width()/2, y, str(y))  
           
matplotlib繪圖的基本設定基本圖-折線圖為例子圖1 畫布建立2 坐标軸、标題設定3 圖例4 添加注釋、數字标簽5 子圖6 其它設定

5 子圖

(1)建立

方法一:建立畫布和子圖(推薦)

fig,axes = plt.subplots(
	nrows=2, ncols=2,   參數名稱可以省略,子圖行列數
	figsize=(xx,xx),	圖表大小
	subplot_kw={},		關鍵字字典
	sharex=False,		設定子圖具有相同的X軸或Y軸。調節xlim/ylim時将影響所有的子圖
	sharey=False,		
	)
axes[0,1]:代表第1行第1列的子圖
           

方法二:先建畫布,再逐個建子圖

fig = plt.figure():空畫布
axes[0,0] = fig.add_subplot(2,2,1):建立子圖,編号從1開始
           

方法三:不建畫布,直接逐個建子圖

plt.subplot(2, 2, 1):2行2列,目前為于第1個位置-區域1
plt.plot(num):在建立的子圖上繪制
plt.subplot(2, 2, 2):2行2列,目前為于第2個位置-區域2
plt.plot(data):在建立的子圖上繪制
           

**(2)其它 **

【子圖間距調整】
plt.subplots_adjust(left=None, bottom=None, right=None, top=None,wspace=None, hspace=None):距離上下左右等的百分比,值越大,圖越小

【坐标軸】
axes[0,0].get_xlim:獲得坐标軸範圍
axes[0,0].set_xlim(n,m) or ([n,m]):設定坐标軸刻度範圍
axes[0, 0].set_xticks([v1,v2,...]):設定x坐标軸刻度,想加刻度标簽先加刻度再加xticklabels,不能少
axes[0, 0].set_xticklabels(['','',..], rotation=30,fontsize=15):對應刻度添加标簽、旋轉角度、大小。設定了标簽就沒有刻度了。
axes[0, 0].tick_params(axis='both', labelcolor='', labelsize=,width=):設定兩個軸上刻度标記的大小、顔色

【軸名稱】
axes[0, 0].set_xlabel('')    
ax.set_ylabel('') :添加坐标軸标簽

【圖例】
axs[0, 1].legend()  :參數同plt.legend()

【标題】
axes[0, 0].set_title('', fontsize=15):添加圖示題

【注釋】
axes[0].text(x,y,string)
axes[0].annotate(string,(x,y))
           

6 其它設定

【網格線】
plt.grid(b=True, which=, axis='y', linewidth, linestyle=)
b:布爾值,是否使用網格線
which:在哪個坐标軸'major' 'minor' 'both'
axis:在哪個坐标軸'x' 'y'  'both'

【儲存】
plt.savefig('名稱.png', bbox_inches='tight',dpi,facecolor,edgecolor): 
格式支援png pdf svg eps ps ;bbox_inches='tight':去除多餘空白,dpi圖像分辨率(每英寸點數)

【全局設定】
plt.rc('對象名稱',對象參數設定/字典形式)
plt.rc('figure',figuresize=(10,10)):設定全部的畫布大小為10*10
第一個參數是對象名稱:'figure'、'axes'、'xtick'、'ytick'、'grid'、'legend'等