全局支持中文顯示以及指定局部中文顯示https://aistudio.baidu.com/aistudio/projectdetail/390895
使用中還有問題可以在論壇中提出(你的問題可能大家已經討論過了)https://ai.baidu.com/forum/topic/show/958873
考慮到部分同學對matplotlib本身不是太熟悉,本文按照局部指定字體的方法匯總了各種圖的案例,方便大家使用。
感謝doubi渣渣同學提出的問題。
本文以2020.04.29日國內現有新型冠狀肺炎確診病例top10省份的數據為例。
準備
# 導入包以及配置中文%matplotlib inlineimport matplotlibimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.font_manager import FontProperties# simhei.ttf的可以替換任意中文ttf字體,注意路徑正確font = FontProperties(fname='simhei.ttf', size=16)# 設置matplotlib正常顯示中文和負號matplotlib.rcParams['font.sans-serif']=['SimHei']matplotlib.rcParams['axes.unicode_minus']=False柱狀圖
# 生成畫布plt.figure(figsize=(10, 6), dpi=80)# 橫坐標城市名稱x = ['黑龍江','香港','臺灣','上海','內蒙古','陝西','北京','山西','廣東','澳門']# 當日現有確診數y = [339, 222, 116, 54, 52, 50, 46, 37, 26, 12]plt.bar(x,y,width=0.5)# 標題plt.title('2020.04.29現有確診數top10', fontproperties=font)# 橫坐標標籤plt.xlabel('top10城市', fontproperties=font)# 中坐標標籤plt.ylabel('現有確診數', fontproperties=font)# 做坐標刻度plt.xticks(x, fontproperties=font)plt.show()
餅圖
# 生成畫布plt.figure(figsize=(10, 6), dpi=80)# 橫坐標城市名稱labels = ['黑龍江','香港','臺灣','上海','內蒙古','陝西','北京','山西','廣東','澳門']# 當日現有確診數sizes = [339, 222, 116, 54, 52, 50, 46, 37, 26, 12]explode = np.linspace(0, 0.4, 10)plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=False, startangle=-45, textprops={'fontproperties':font})plt.title("2020.04.29現有確診數top10城市佔比", fontproperties=font)# 圖例plt.legend(loc='right', bbox_to_anchor=[0.75, 0.4, 0.5, 0.5], prop=font)plt.show()