今天又學習了兩種新的圖形繪制方法,并且學會了全局設定中文字型的方法。
全局中文字型設定及負數顯示問題
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'SimHei'#SimHei是一種中文字型
如果顯示出來是一些小方塊而不是中文,那是因為在matplotlib的配置檔案下沒有找到合适的中文字型
解決方法如下:
1.在C:\Users\ht\Anaconda3\Lib\site-packages\matplotlib\mpl-data檔案下找到matplotlibrc
2.找到font.sans-serif,在後面直接添加中文字型後儲存即可。
例如:SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif等,都是中文字型。
負數顯示:
餅狀圖繪制
題目描述:
代碼實作:
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm #用來導入圖例
from itertools import groupby #用來分組
#統一設定圖形中中文字型
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'SimHei'
#每門課成績
scores={'資料結構':[89,70,49,87,92,84,73,71,78,81,90,37,77,82,81,79,80,82,75,90,54,80,70,60,61],
'線性代數':[70,74,80,60,50,87,68,77,95,80,79,74,69,64,82,81,78,90,78,79,72,69,45,70,70],
'英語':[83,87,69,55,80,89,96,81,83,90,54,70,79,66,85,82,88,76,60,80,75,83,75,70,20],
'python':[90,60,82,79,88,92,85,87,89,71,45,50,80,81,87,93,80,70,68,65,85,89,90,72,75]}
#自定義分組函數
def splitScore(score):
if score>=85:
return '優'
elif score>=60:
return '及格'
else:
return '不及格'
#統計每門課程中優,及格,不及格的人數
ratios=dict()#定義一個空字典
for subject,subjectScore in scores.items():#items傳回多個元素,每個元素包括鍵和值
ratios[subject]={}
#groupby()函數需要對原始資料進行排序才能正确分類
for category,num in groupby(sorted(subjectScore),splitScore):
ratios[subject][category]=len(tuple(num))#tuple傳回對應類别的成績數目
#ratios的格式為{'課程名稱':{'優':3,'及格':5,'不及格':1}}
#建立四個子圖
fig,axs=plt.subplots(2,2)#把繪圖區域分成兩行兩列
axs.shape=4
for index,subjectData in enumerate(ratios.items()):#獲得下标來選擇往哪一個子圖繪制
plt.sca(axs[index])
subjectName,subjectRatio=subjectData#把subjectData的第一項交給subjecName,第二項交給subjectRatio
#用函數pie繪制餅狀圖
plt.pie(list(subjectRatio.values()),#每個扇形對應的數值
labels=list(subjectRatio.keys()),#每個扇形的标簽
autopct='%1.1f%%')#百分比格式顯示 第一個百分号表示要引導一個格式,f表示實數,最後兩個百分号顯示為一個百分号,.1表示保留一位小數
plt.xlabel(subjectName)#每個扇形的名稱
plt.legend()#自動生成圖例
plt.gca().set_aspect('equal')#設定縱橫比相等
plt.show()
生成圖像:
雷達圖繪制
題目描述:
代碼實作:
import numpy as np
import matplotlib.pyplot as plt
#設定全局中文字型
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'SimHei'
#某學生的課程與成績
courses=['c++','python','高數','大學英語','軟體工程','組成原理','數字圖像處理','計算機圖形學']
scores=[80,95,78,85,45,65,80,60]
datalength=len(scores)
#angles數組把圓周等分成datalength份
#linspace用來生成等差數組
angles=np.linspace(0, #數組第一個資料
2*np.pi, #數組最後一個資料
datalength, #數組中資料數量
endpoint=False #不包含終點
)
scores.append(scores[0])#清單尾部追加scores數組第一個資料80
angles=np.append(angles,angles[0])#angles數組尾部追加第一個角度
#繪制雷達圖polar
plt.polar(angles, #設定角度
scores, #設定個角度上的資料 角度的資料共同确定一個點
'rv--', #設定顔色,線型和端點符号
linewidth=2)#設定線寬
#設定角度網絡标簽thetagrids
plt.thetagrids(angles*180/np.pi,#轉換成角度
courses, #對應角度設定對應課程名稱
)
#填充雷達圖内部
plt.fill(angles,
scores,
facecolor='r',#填充顔色
alpha=0.3)#顔色透明度
plt.show()
三維圖形繪制
題目描述:
代碼實作:
import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D #導入相應對象
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'SimHei' #設定全局字型
plt.rcParams['axes.unicode_minus']=False #解決負數顯示問題
#聲明要建立三維子圖
fig=plt.figure()
ax=fig.gca(projection='3d')
#生成測試資料
theta=np.linspace(-4*np.pi,4*np.pi,100)#100個資料的等差數組
z=np.linspace(-4,4,100)*0.3
r=z**4+1
x=r*np.sin(theta)
y=r*np.cos(theta)
#繪制三位曲線,設定标簽
ax.plot(x,y,z,'rv-',label='參數曲線')
#設定圖例字号
mpl.rcParams['legend.fontsize']=10
ax.legend()#生成圖例
plt.show()
圖像顯示: