2024 解决matplotlib中文字体问题

本文介绍了在PythonMatplotlib库中使用SimHei字体时遇到的错误,以及提供了解决方案:一是通过`font_manager`指定字体路径,二是直接在plot函数中指定fontproperties,三是全局设置matplotlib字体为SimHei。
摘要由CSDN通过智能技术生成

第一种代码(失败代码)

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font_path = '/Users/huangbaixi/Desktop/SimHei.ttf'

def plot_demo():
    #print(mpl.get_cachedir())
    # 绘制折线图
    font_prop = FontProperties(fname=font_path)
    plt.rcParams['font.sans-serif'] = [font_prop.get_name()]
    plt.rcParams['axes.unicode_minus'] = False
    year = [2017, 2018, 2019, 2020]
    people = [20, 40, 60, 70]
    # 生成图表
    plt.plot(year, people)
    plt.xlabel('年份')
    plt.ylabel('人口')
    plt.title('人口增长')
    # 设置纵坐标刻度
    plt.yticks([0, 20, 40, 60, 80])
    # 设置填充选项:参数分别对应横坐标,纵坐标,纵坐标填充起始值,填充颜色
    plt.fill_between(year, people, 20, color='green')
    # 显示图表
    # plt.savefig("./plt.png")
    plt.show()

这一版代码会出现

findfont: Generic family ‘sans-serif’ not found because none of the following families were found: SimHei

查询发现:
在这里插入图片描述

rcParams 有概率失败

第二种方法(指定应用)

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font_path = '/Users/huangbaixi/Desktop/SimHei.ttf'
font_prop = FontProperties(fname=font_path)

def plot_demo():
    year = [2017, 2018, 2019, 2020]
    people = [20, 40, 60, 70]

    plt.plot(year, people)
    plt.xlabel('年份', fontproperties=font_prop)
    plt.ylabel('人口', fontproperties=font_prop)
    plt.title('人口增长', fontproperties=font_prop)
    plt.yticks([0, 20, 40, 60, 80])
    plt.fill_between(year, people, 20, color='green')
    plt.show()

plot_demo()

这是成功的。
在这里插入图片描述

第三种方法(全局应用)

import matplotlib
# font_path = '/usr/share/fonts/SimHei.ttf'
font_path = '/Users/huangbaixi/Desktop/SimHei.ttf'
# 添加字体路径
matplotlib.font_manager.fontManager.addfont(font_path)

# 设置 matplotlib 的全局参数
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 使用 SimHei 字体
matplotlib.rcParams['axes.unicode_minus'] = False  # 正常显示负号

# 定义绘图函数
def plot_demo():
    year = [2017, 2018, 2019, 2020]
    people = [20, 40, 60, 70]

    plt.plot(year, people)
    plt.xlabel('年份')
    plt.ylabel('人口')
    plt.title('人口增长')
    plt.yticks([0, 20, 40, 60, 80])
    plt.fill_between(year, people, 20, color='green')
    plt.show()

这也是可以的。

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值