plt.rcParams(可解决matplotlib无法显示中文和负号的问题)

plt.rcPrarms的使用方法以及能解决的问题

import matplotlib.pyplot as plt
import matplotlib

字体

matplotlib.rcParams[‘font.family’] = ‘SimHei’ #设置字体
matplotlib.rcParams[‘font.size’] = 10 #设置字体大小
matplotlib.rcParams[‘axes.unicode_minus’]=False #坐标轴的负号正常显示

样式

plt.rcParams[‘font.stretch’] = ‘normal’
plt.rcParams[‘font.style’] = ‘normal’
plt.rcParams[‘font.variant’] = ‘normal’
plt.rcParams[‘font.weight’] = ‘normal’

找到matplotlib包的所在位置,一般在C:\Users****\AppData\Roaming\Python\Python39\site-packages\matplotlib\mpl-data,里面有个配置文件,matplotlibrc,用notepad++打开。在里面找到相应的地方改掉

显示负号:

原先:#axes.unicode_minus : True
改成:axes.unicode_minus : False

正式显示中文:

#font.family : sans-serif 去掉#号

#font.sans-serif : Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Anal, Helvetica, Avant Ga
font.sans-serif : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Anal, Helvetica, Avant Ga

→去掉#号,并在:号后加入SimHei

另外,如果在使用了系统内置样式的时候全局设置完了还是出错
建议在每次使用中文时增加一个属性:fontproperties

ax.set_title(“平方数”, fontproperties=‘SimHei’, fontsize=24)
ax.set_xlabel(“值”, fontproperties=‘SimHei’, fontsize=14)
ax.set_ylabel(“值的平方”, fontproperties=‘SimHei’, fontsize=14)

注:如何找到字体存储路径,在matplotlibrc的路径的 ****\fonts\ttf

查找字体路径

print(matplotlib.matplotlib_fname())

查找字体缓存路径

print(matplotlib.get_cachedir())

拓展问题:
import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5]
square = [1, 4, 9, 16, 25]

fig, ax = plt.subplots() # fig 整张图片 ax 图片中的各个图表
ax.plot(input_values,square, linewidth=3)

ax.set_title(“平方数”, fontsize=24)
ax.set_xlabel(“值”, fontsize=14)
ax.set_ylabel(“值的平方”, fontsize=14)
ax.tick_params(axis=‘both’, labelsize=14)

plt.show()
很明显无法找到字体

chr(24179)

能看出 24179 是 ASCII码 缺少字体
添加
plt.rcParams[‘font.sans-serif’] = [‘SimHei’] # 手动选择字体,显示中文标签
plt.rcParams[‘axes.unicode_minus’] = False
解决问题
rcParams的属性:

属性 说明
font.family 用于显示字体的名称
font.style 字体风格,正常’normal’或斜体’italic’
font.size 字体大小,整数字号或者’large’、’x-small’

font.family的属性值:

属性值 说明
SimHei 中文黑体
Kaiti 中文楷体
Lisu 中文隶书
FangSong 中文仿宋
YouYuan 中文幼圆
STSong 华文宋体

  • 12
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值