当前位置:   article > 正文

一文解决Matplotlib中英文使用不同字体的最优解_matplotlib中英文不同字体

matplotlib中英文不同字体

一文解决Matplotlib中英文使用不同字体的最优解

中英文使用不同字体

我们需要解决两个需求:

  1. 第一个需求:要用中文字体显示中文,不能全部都是框框。
  2. 第二个需求:横纵坐标的数字用英文字体显示,英文用英语字体显示。

环境matplotlib 3.6.3

方法很简单,只需要添加一行,前者是matplolib默认的英文字体,后者是中文字体黑体:

plt.rcParams['font.family'] = ['DejaVu Sans','SimHei']
  • 1

以此类推可以把英文字体改成SimSun,英文字体改成Times New Roman
要查看自己的font family,可以使用代码(参考来源:链接):

from matplotlib.font_manager import FontManager
mpl_fonts = set(f.name for f in FontManager().ttflist)
print('all font list get from matplotlib.font_manager:')
for f in sorted(mpl_fonts):
    print('\t' + f)
  • 1
  • 2
  • 3
  • 4
  • 5

具体示例:

import matplotlib.pyplot as plt
plt.rcParams['font.family'] = ['DejaVu Sans','SimHei']
# 绘制图像
plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
plt.title('中文和English')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

效果(图中英文为DejaVu Sans,中文为宋体):
图中英文为DejaVu Sans,中文为宋体

全局是中文字体,公式为英文字体

import matplotlib.pyplot as plt
plt.rcParams['mathtext.fontset'] = 'stix'  # 设置数学公式字体为stix
plt.rcParams['font.family'] = ['SimSun']
# 绘制图像
plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
plt.title('我是中文English$a+b=c$')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

这个时候只有公式是英文字体:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/423145
推荐阅读
相关标签
  

闽ICP备14008679号