詳解matplotlib中顯示中文的有效方法,需要具體代碼示例
在數(shù)據(jù)可視化中,matplotlib是一個(gè)非常常用的庫(kù),它提供了強(qiáng)大且靈活的繪圖功能。然而,matplotlib默認(rèn)不支持顯示中文字符,這給使用者帶來(lái)了不便。本文將介紹一些在matplotlib中顯示中文的有效方法,并提供具體的代碼示例。
方法一:使用系統(tǒng)字體
matplotlib可以通過(guò)設(shè)置系統(tǒng)字體路徑來(lái)實(shí)現(xiàn)顯示中文。首先,我們需要找到系統(tǒng)中對(duì)應(yīng)的字體文件,比如微軟雅黑字體的路徑為”C:/Windows/Fonts/msyh.ttc”。
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='C:/Windows/Fonts/msyh.ttc')
plt.rcParams['font.family'] = font.get_name()
# 繪圖代碼
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.xlabel('橫軸', fontproperties=font)
plt.ylabel('縱軸', fontproperties=font)
plt.title('示例圖', fontproperties=font)
plt.show()
登錄后復(fù)制
方法二:使用自定義字體
如果系統(tǒng)中沒(méi)有對(duì)應(yīng)的字體文件,我們可以將需要的字體文件放在當(dāng)前目錄下,使用自定義字體來(lái)顯示中文。
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='myfont.ttf')
plt.rcParams['font.family'] = font.get_name()
# 繪圖代碼
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.xlabel('橫軸', fontproperties=font)
plt.ylabel('縱軸', fontproperties=font)
plt.title('示例圖', fontproperties=font)
plt.show()
登錄后復(fù)制
方法三:使用中文顯示模塊
在matplotlib中,有一些第三方模塊可以直接用來(lái)顯示中文,如matplotlib-chinafonts和matplotlib-charset等。這些模塊可以通過(guò)pip命令安裝,并按照說(shuō)明使用。
import matplotlib.pyplot as plt
import matplotlib.font_manager as mfm
font_path = "C:/Windows/Fonts/msyh.ttc"
prop = mfm.FontProperties(fname=font_path)
plt.rcParams['font.family'] = prop.get_name()
# 繪圖代碼
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.xlabel('橫軸', fontproperties=prop)
plt.ylabel('縱軸', fontproperties=prop)
plt.title('示例圖', fontproperties=prop)
plt.show()
登錄后復(fù)制
總結(jié):
在使用matplotlib進(jìn)行數(shù)據(jù)可視化時(shí),顯示中文是一個(gè)常見(jiàn)需求。本文介紹了三種在matplotlib中顯示中文的有效方法,并提供了具體的代碼示例。通過(guò)設(shè)置系統(tǒng)字體路徑、使用自定義字體以及使用第三方中文顯示模塊,我們可以輕松地實(shí)現(xiàn)中文的顯示。希望讀者能夠在使用matplotlib時(shí)盡情使用中文,提升數(shù)據(jù)可視化的效果!






