matplotlib.pyplot中文字型顯示
阿新 • • 發佈:2019-01-08
方法1:
import matplotlib
font = {'family': 'MicroSoft Yahei',
'weight': 'bold',
'size': 12}
matplotlib.rc("font", **font)
例項:
import matplotlib import matplotlib.pyplot as plt import random font = {'family': 'MicroSoft Yahei', 'weight': 'bold', 'size': 12} matplotlib.rc("font", **font) x = range(0, 120) y = [random.randint(20,35) for i in range(120)] plt.figure(figsize = (20, 8), dpi = 80) plt.plot(x, y) # 調整x軸刻度 _x = list(x)[::3] _xtick_labels = ["10點{}分".format(i) for i in range(60)] _xtick_labels += ["11點{}分".format(i) for i in range(60)] # 取步長,數字和字串一一對應,資料長度一樣 plt.xticks(_x, _xtick_labels[::3], rotation = 45) # rotation 旋轉角度 plt.show()
執行結果:
方法2:
import matplotlib
matplotlib.rc("font", family = "MicroSoft YaHei", weight = "bold")
例項:
import matplotlib import matplotlib.pyplot as plt import random matplotlib.rc("font", family = "MicroSoft YaHei", weight = "bold") x = range(0, 120) y = [random.randint(20,35) for i in range(120)] plt.figure(figsize = (20, 8), dpi = 80) plt.plot(x, y) # 調整x軸刻度 _x = list(x)[::3] _xtick_labels = ["10點{}分".format(i) for i in range(60)] _xtick_labels += ["11點{}分".format(i) for i in range(60)] # 取步長,數字和字串一一對應,資料長度一樣 plt.xticks(_x, _xtick_labels[::3], rotation = 60) # rotation 旋轉角度 plt.show()
執行輸出:
方法3:
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname='/System/Library/Fonts/PingFang.ttc")
# 不同系統,路徑有所不同,事先查找出系統中可用的中文字型以及路徑
# 呼叫
plt.func(...,fontproperties=my_font)
注:Linux/Mac下字型檢視:
fc-list :lang=zh # 冒號前有空格
以Ubuntu為例:
例項:
import matplotlib import matplotlib.pyplot as plt from matplotlib import font_manager import random my_font = font_manager.FontProperties(fname=r"C:\Windows\Fonts\STFANGSO.TTF") x = range(0, 120) y = [random.randint(20,35) for i in range(120)] plt.figure(figsize = (20, 8), dpi = 80) plt.plot(x, y) # 調整x軸刻度 _x = list(x)[::3] _xtick_labels = ["10點{}分".format(i) for i in range(60)] _xtick_labels += ["11點{}分".format(i) for i in range(60)] # 取步長,數字和字串一一對應,資料長度一樣 plt.xticks(_x, _xtick_labels[::3], FontProperties = my_font, rotation = 90) # rotation 旋轉角度 plt.show()
執行結果: