Correctly displaying Chinese characters in matplotlib is a problem often encountered by many Chinese users. By default, matplotlib uses English fonts and cannot display Chinese characters correctly. To solve this problem, we need to set the correct Chinese font and apply it to matplotlib.
The following are some specific code examples to help you display Chinese characters correctly in matplotlib.
First, we need to import the required libraries:
import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties
Next, we need to select a Chinese font and set it as the default font of matplotlib. You can choose a font that conforms to Chinese habits according to your own needs, such as bold, Song, etc.
# 设置中文字体 font = FontProperties(fname="/usr/share/fonts/yourfont.ttf")
Note that in the above code, /usr/share/fonts/yourfont.ttf
is an example path, you need to replace it with the Chinese font file that actually exists on your computer path.
Then, we can start drawing graphics and use Chinese characters in graphics.
# 创建一个图形对象 fig, ax = plt.subplots() # 在图形中添加中文文字 ax.text(0.5, 0.5, "你好,世界!", fontproperties=font, fontsize=14) # 显示图形 plt.show()
In this example, we use the ax.text
method to add a Chinese character "Hello, world!" to the graphic. Apply the previously set Chinese font to this text through the fontproperties
parameter.
Run the above code, you should be able to see a graphics window containing Chinese characters pop up, and the Chinese characters can be displayed correctly.
In addition to the methods of setting Chinese fonts mentioned above, there are other methods that can also help you correctly display Chinese characters in matplotlib, such as using the Chinese fonts that come with the system and using mpl. rcParams
to set the default font, etc. The specific method can be based on your needs to choose a solution that suits you.
To summarize, to display Chinese characters correctly in matplotlib, we need to first select a Chinese font and set it as the default font of matplotlib; then, use fontproperties## during the drawing process #Parameter applies Chinese fonts to places where Chinese characters need to be displayed.
The above is the detailed content of Correct way to display Chinese characters in matplotlib. For more information, please follow other related articles on the PHP Chinese website!