Fundamentals 2 min read

How to Display Chinese Characters in Matplotlib Plots (Step‑by‑Step)

Matplotlib does not render Chinese text by default, showing squares instead, but you can fix this by setting a Chinese font directly in code, adjusting rcParams, or editing the config file; the example demonstrates loading a local font file and applying it to axis labels and titles.

Model Perspective
Model Perspective
Model Perspective
How to Display Chinese Characters in Matplotlib Plots (Step‑by‑Step)

Matplotlib does not display Chinese characters by default, resulting in small squares instead of the intended text. To correctly show Chinese in plots, you can (1) specify a font directly in the program, (2) modify the rcParams dictionary at the start of the script, or (3) edit the Matplotlib configuration file.

<code>from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import numpy as np
font = FontProperties(fname="C:/Windows/Fonts/STXINGKA.TTF")

x = np.linspace(0, 10, 100)
y = x**2 - 2 * x
plt.plot(x, y, label='$y=x^2-2x$')
plt.xlabel('横坐标', fontproperties=font)
plt.ylabel('纵坐标', fontproperties=font)
plt.title('标题', fontproperties=font)
plt.legend()
</code>

In the code above, the font = FontProperties(fname="C:/Windows/Fonts/STXINGKA.TTF") line sets the font to a Chinese typeface located in the system’s font directory; STXINGKA refers to the "华文行楷" font. For Windows systems, a simpler alternative is to set the font family at the beginning of the script, e.g., plt.rcParams['font.family'] = ['SimHei'] , which uses the SimHei (Microsoft YaHei) font.

Reference: 朱顺泉, 《经济金融数据分析及其Python应用》

pythonData VisualizationMatplotlibChinese charactersFont settings
Model Perspective
Written by

Model Perspective

Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.