简单易行的matplotlib中英文混排(设置中文为宋体,英文为times new roman)

先看效果:

  • 普通混排
  • 支持tex文本的混排:

以下是代码:

  • 普通混排

    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    # 设置字体
    plt.rcParams['font.family'] = ['SimSun', 'Times New Roman'] # 设置字体族,中文为SimSun,英文为Times New Roman
    plt.rcParams['mathtext.fontset'] = 'stix' # 设置数学公式字体为stix
    # 绘制图像
    plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
    plt.title('这是一个中英文混排的标题') # 使用宋体字体显示中文标题
    plt.xlabel('X轴') # 使用宋体字体显示中文X轴标签
    plt.ylabel('Y轴') # 使用宋体字体显示中文Y轴标签
    plt.show()
    

    或者明确指定字体ttc的路径:

    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    # 设置字体
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) # 设置中文字体为宋体
    plt.rcParams['font.family'] = 'Times New Roman' # 设置英文字体为Times New Roman
    # 绘制图像
    plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
    plt.title('这是一个中英文混排的标题', fontproperties=font) # 使用宋体字体显示中文标题
    plt.xlabel('X轴', fontproperties=font) # 使用宋体字体显示中文X轴标签
    plt.ylabel('Y轴', fontproperties=font) # 使用宋体字体显示中文Y轴标签
    plt.show()
    
    
  • 支持tex的混排:

    import matplotlib.pyplot as plt
    plt.rcParams['font.family'] = ['SimSun', 'Times New Roman'] # 设置字体族,中文为SimSun,英文为Times New Roman
    plt.rcParams['mathtext.fontset'] = 'stix' # 设置数学公式字体为stix
    
    # 以下为示例代码
    x = [1, 2, 3, 4]
    y = [10, 20, 30, 40]
    plt.plot(x, y)
    plt.xlabel('横轴 (X)', fontsize=14)
    plt.ylabel(r'纵轴 ($\rm mg \cdot L^{-1}$)', fontsize=14)
    plt.title('Tex中英混排示例图', fontsize=16)
    plt.show()
    

版权声明:本文为博主作者:月司原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/yue81560/article/details/129434347

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2024年5月6日
下一篇 2024年5月6日

相关推荐

此站出售,如需请站内私信或者邮箱!