Windows下的matplotlib画图中文显示设置

时间:2023-03-09 15:34:11
Windows下的matplotlib画图中文显示设置

一、在测试matplotlib时遇到X轴中文字符不显示的问题,参考网上

源代码如下

from matplotlib import pyplot as plt
import random
import matplotlib
from matplotlib import font_manager # my_font = {'family' : 'MicroSoft YaHei',
# 'weight' : 'bold',
# 'size' : 'larger'}
# matplotlib.rc("font",**my_font)
# matplotlib.rc("font",)
my_font = font_manager.FontProperties(fname="C:\\Windows\\Fonts\\msyh.ttf") plt.figure(figsize=(,),dpi=) x = range(,)
y = [random.randint(,) for i in range()] _xticks_labels = ["10点{}分".format(i) for i in range()]
_xticks_labels += ["11点{}分".format(i) for i in range()]
# plt.xticks(list(x)[::])
plt.xticks(list(x)[::],_xticks_labels[::],rotation=,fontproperties=my_font)
plt.plot(x,y)
plt.show()

二、参考网上玩法

电脑环境:Windows7-64bit,Anaconda3-4.2.0(对应python 3.5.2版本),IDE是Anaconda自带的Spyder 3。

1、找到Windows系统自带的字体库目录,默认在C:\Windows\Fonts目录下。

Windows下的matplotlib画图中文显示设置

2、选择你自己喜欢的字体,然后“右键”→“属性”,可以看到该字体的名字。

本教程以微软雅黑字体为例,您也可以选择其他字体,如果自带的字体库满足不了您的需求,您可以网上下载其他字体,将字体解压到C:\Windows\Fonts目录即可。

Windows下的matplotlib画图中文显示设置

3、在IDE工具中,导入matplotlib库,开始定义字体所在路径。

  • 1 先不设置参数,可以看到中文字体显示为方框(此处使用的是SVC三分类模型)。
Windows下的matplotlib画图中文显示设置
Windows下的matplotlib画图中文显示设置
  • 2 设置参数之后,可以看到中文字体可以正常显示了。(代码经过测试,可放心使用)

哪里需要中文设置,保证该函数里有fontproperties = my_font参数即可。比如x轴的标签为:鸢尾花的花萼长度。那么可以使用:

plt.xlabel('鸢尾花的花萼长度', fontproperties = my_font)
Windows下的matplotlib画图中文显示设置
Windows下的matplotlib画图中文显示设置
# coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets # 以下两行是解决常见的其他问题
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 import matplotlib.font_manager as mf # 导入字体管理器
my_font= mf.FontProperties(fname='C:\\Windows\\Fonts\\msyh.ttf') # 加载字体 iris = datasets.load_iris()
X = iris.data[:, :2]
Y = iris.target def my_kernel(X, Y):
M = np.array([[2, 0], [0, 1.0]])
return np.dot(np.dot(X, M), Y.T) h = 0.02 clf = svm.SVC(kernel = my_kernel)
clf.fit(X, Y) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.title('测试!!!3-Class classification using SVM with custom kernel',
fontproperties = my_font)
plt.axis('tight')
plt.show()
Windows下的matplotlib画图中文显示设置
Windows下的matplotlib画图中文显示设置