主要使用matplotlib包里的pyplot函數進行繪圖
寫在前面
通過python進行繪圖經常會遇到圖中的中文無法正常顯示,坐標軸的負數無法正常顯示問題,以下是解決方案:
先查看當下系統有哪些字體
import matplotlib
mpl_fonts=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
print('all font list get from matplotlib.font_manager:')
for fonts in mpl_fonts:
print('\t' + fonts)
打印結果:
繪圖函數中進行相應設置
從上述打印出來的結果選擇合適字體
import matplotlib.pyplot as plt
# plt.rcParams['font.family'] = 'SimHei' # windows系統可選
plt.rcParams['font.sans-serif'] = ['Arial Black']
plt.rcParams['axes.unicode_minus'] = False # 解決負數無法正常顯示的問題
matplotlib.pyplot.figure()函數
# 創建一個新畫布,或者激活一個現有畫布
matplotlib.pyplot.figure(num=None,
figsize=None, # 設置畫布的寬度和高度 eg:(4,6)
dpi=None, # 設置圖形分辨率 默認值
facecolor=None, # 背景色,默認'white'
edgecolor=None, # 邊框顏色,默認'white'
frameon=True, # bool,如果為False,則禁止繪制圖形框
FigureClass=<class 'matplotlib.figure.Figure'>,
clear = False,
**kwargs
)
常用函數
plt.rcParams["font.family"]="SimHei" # win系統設置字體
plt.rcParams['font.sans-serif'] = ['Arial Black'] # mac系統設置字體
plt.rcParams['axes.unicode_minus'] = False # 作用就是解決負號'-'顯示為方塊的問題
#設置刻度范圍
ax.set_xlim(1,7.1) #x軸從1到7.1
ax.set_ylim(40,100) #y軸從40到100
ax.set_xticks() # 設置顯示的刻度
ax.set_yticks()
# 設置刻度標簽
ax.set_xticklebels()
ax.set_yticklebels()
# 添加坐標軸標簽
ax.set_xlabel()
ax.set_ylabel()
# 設置表頭
ax.set_title()
# 添加圖例
ax.legend()
# 可以裝修軸上的刻度線和軸標簽
ax.tick_params()
ax.spines["top"].set_visible(False) # 不顯示圖的上軸
ax.spines["right"].set_visible(False) # 右
ax.spines["left"].set_visible(False) # 左
ax.spines["bottom"].set_linewidth(3) # 底軸線條寬度設置
ax.spines["left"].set_color("darkblue") # 設置左軸的顏色
ax.text() # 指定位置添加標簽
ax.annotate() # 添加箭頭的標注函數annotate()
# 保存為jpg文件
plt.savefig("figure.jpg")#我這里填的是相對路徑,如果想保存在指定文件夾下,填寫絕對路徑。
# 保存為png文件
plt.savefig("figure.png")
創建畫布
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig = plt.figure(num=1,figsize=(4,4))
plt.plot([1,2,3,4],[1,2,3,4])
plt.show()
新增畫布
fig=plt.figure(num=1,figsize=(4,4))
ax1=fig.add_subplot(221)###可從圖中看到,我們的畫布是分為2x2的區域
ax1.plot([1,2,3,4],[1,2,3,4])
ax2=fig.add_subplot(222)
ax2.plot([1,2,3,4],[2,2,3,4])
ax3=fig.add_subplot(223)
ax3.plot([1,2,3,4],[1,2,2,4])
ax4=fig.add_subplot(224)
ax4.plot([1,2,3,4],[1,2,3,3])
plt.show()
import matplotlib.gridspec as gridspec #調用網格
fig=plt.figure(figsize=(4,6)) #創建畫布
gs=gridspec.GridSpec(3,3)#設定網格
ax1=fig.add_subplot(gs[0,:])#選定網格
ax1.plot([1,2,3,4],[1,2,3,4])
ax2=fig.add_subplot(gs[1,:-1])
ax2.plot([1,2,3,4],[1,2,3,4])
ax3=fig.add_subplot(gs[1:,-1])
ax3.plot([1,2,3,4],[1,2,3,4])
ax4=fig.add_subplot(gs[2,0])
ax4.plot([1,2,3,4],[1,2,3,4])
ax5=fig.add_subplot(gs[2,1])
ax5.plot([1,2,3,4],[1,2,3,4])
plt.show()
栗子
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # mac系統
plt.rcParams['axes.unicode_minus'] = False # 作用就是解決負號'-'顯示為方塊的問題
# 創建數據
app=[78,80,79,81,91,95,96]
x=np.arange(1,8)
# 創建畫布
fig=plt.figure(figsize=(10,6))
# 創建子畫布
ax=fig.add_subplot(111)
# ax.plot(x,app)
ax.plot(x,app,"r-.d",label="蘋果")#在原來的基礎上添加“r-.d”
# 在原圖上新增其他線條
ban=[70,80,81,82,75,90,89]
ax.plot(x,ban,"c-d",label="香蕉")
# 設置軸范圍
ax.set_xlim([1,7.1])
ax.set_ylim([40,100])
ax.set_xticks(np.linspace(1,7,7))
ax.set_yticks(np.linspace(50,100,6))#可調控字體大小,樣式,
# 設置刻度標簽
ax.set_xticklabels(["星期一","星期二","星期三","星期四","星期五","星期六","星期日"],fontproperties='Arial Unicode MS',\
fontsize=12,rotation=10) #參數rotation=10,可以使得類標旋轉值為10的角度
ax.set_yticklabels(["50kg","60kg","70kg","80kg","90kg","100kg"])
# 設置刻度參數
ax.tick_params(left=False,pad=8,direction="in",length=2,width=3,color="b",labelsize=12)
ax.tick_params("x",labelrotation=10)#類標旋轉
# 設置軸標簽
ax.set_xlabel("星期")#添加x軸坐標標簽,后面看來沒必要會刪除它,這里只是為了演示一下。
ax.set_ylabel("銷售量",fontsize=16)#添加y軸標簽,設置字體大小為16,這里也可以設字體樣式與顏色
# 設置圖標題
ax.set_title("某某水果店一周水果銷售量統計圖",fontsize=18, backgroundcolor='#3c7f99',fontweight='bold',color='white',verticalalignment="baseline")#標題(表頭)
# 設置軸線條寬度
ax.spines["bottom"].set_linewidth(3)#底軸線條寬度設置
ax.spines["top"].set_visible(False)#上軸不顯示
ax.spines["right"].set_visible(False)#右
ax.spines["left"].set_visible(False)#左
# 設置圖例
ax.legend(loc=3,labelspacing=0.5,handlelength=1.5,fontsize=12,shadow=True)
# ax.legend(["蘋果"],loc=3,labelspacing=0.5,handlelength=1.5,fontsize=12,shadow=True)
# 一般添加圖例時,會在畫圖的函數里,比如ax.plot()函數中添加一個label參數,則后面直接ax.legend(loc="")
# 不需要第一個參數了。
# loc的可取"best",1或者"upper right",2或"upper left",3或"lower left",4或"lower right",代表放不同位置
ax.annotate(s="min:70",xy=(1,70),xytext=(1.3,66),arrowprops=dict(facecolor="y",shrink=0.05,
headwidth=12,headlength=6,width=4),fontsize=12)
# 標記特殊值
ax.text(7,97,"max:96",fontsize=14,color="g",alpha=1)
ax.text(6,86,"max:90",fontsize=12,alpha=1)
plt.show()
# plt.savefig(r"D:\Users\Desktop\python\figure.png")