【python3】【matplotlib】【绘制折线图】【解决中文乱码】【设置线条样式】

Background

我在win10环境下的pycharm中开发好的程序,设置字体后可以正常显示中文,但是部署到Linux服务器上却提示错误提示,最终发现原因是:pyplot 默认不支持显示中文字体,且未自带中文字体,因此需要自行下载所需字体,并修改 rcParams 参数来显示中文。

中文乱码

《【python3】【matplotlib】【绘制折线图】【解决中文乱码】【设置线条样式】》

设置中文字体

《【python3】【matplotlib】【绘制折线图】【解决中文乱码】【设置线条样式】》

1、源码

注意: 代码顺序,先设置再绘图

from matplotlib import pyplot as plt

if __name__ == '__main__':
    # x轴和y轴数据
    xl = [15.123, 13.547, 12.864, 12.113]
    yl = [-3.423, -2.123, -1.723, -0.523]

    # 设置图的大小
    plt.figure(figsize=(12.7, 5.7))
    # 用来正常显示中文标签
    plt.rcParams['font.family'] = 'SimHei'
    # 用来正常显示负号
    plt.rcParams['axes.unicode_minus'] = False

    # 绘制折线图
    plt.plot(xl, yl, label='YL-001', marker='o')
    ax = plt.gca()
    # 设置x轴标签显示在上面
    ax.xaxis.set_ticks_position('top')
    # 设置下边线不显示
    ax.spines['bottom'].set_visible(False)
    # 设置标题和字体大小
    plt.title('监测数据成果曲线图', fontsize=15)
    # 设置图例位置
    plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0)
    # 设置显示x轴网格线
    plt.grid(axis="x")
    # 显示图表
    plt.show()

2、Linux服务器字体安装脚本 install_font.py

把该脚本和字体文件放在同一目录下,然后执行安装命令:python3 install_font.py。需要什么字体可以自己下载,我这里给出几个常用的字体。

import shutil

import matplotlib


def copy_font_file():
    """ 把下在的字体文件拷贝到 matplotlib 的字体路径下 :return: """
    font_file = 'SimHei.ttf'
    suffix = '/fonts/ttf'
    mt_lib_path = matplotlib.matplotlib_fname()
    idx = mt_lib_path.rindex('/')
    mt_font_path = mt_lib_path[:idx] + suffix
    shutil.copy(font_file, mt_font_path)


def del_font_cache():
    """ 删除 matplotlib 的字体缓存路径 :return: """
    dir_cache = matplotlib.get_cachedir()
    shutil.rmtree(dir_cache)


if __name__ == '__main__':
    try:
        copy_font_file()
        del_font_cache()
        print('font install success')
    except:
        print('font install failed')

3、几种常用的中文字体

下载地址:https://pan.baidu.com/s/1A1APUP3QNmEAtLM6fxOlIQ
提取码:king

《【python3】【matplotlib】【绘制折线图】【解决中文乱码】【设置线条样式】》

英文名称中文字体
SimHei中文黑体
Kaiti中文楷体
LiSu中文隶书
FangSong中文仿宋
YouYuan中文幼圆
STSong华文宋体

4、线条常用marker

《【python3】【matplotlib】【绘制折线图】【解决中文乱码】【设置线条样式】》

    原文作者:WaiSaa
    原文地址: https://blog.csdn.net/qq_42761569/article/details/120899408
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞