0

I'm using Matplotlib to create a plot, and I would like to set the font for the labels of each line in the plot. I have Chinese characters in my labels and want to ensure they are displayed correctly.

Here's the code snippet I'm working with:

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname="/path/anaconda3/envs/env_name/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf")

x = [1, 2, 3, 4]
y1 = [5, 6, 7, 8]
y2 = [8, 7, 6, 5]


plt.plot(x, y1, label='曲线1')
plt.plot(x, y2, label='曲线2')


plt.xlabel('横轴', fontproperties=font)
plt.ylabel('纵轴', fontproperties=font)
plt.title('标题', fontproperties=font)


plt.legend()
plt.savefig('plot.png')
plt.show()

enter image description here

I would like to set the font for the labels '曲线1' and '曲线2' to display the Chinese characters correctly. How can I achieve this in Matplotlib?

Thank you for your assistance, and apologies for any confusion caused.

XiaoBanni
  • 81
  • 7
  • 1
    [This](https://stackoverflow.com/questions/47112522/matplotlib-how-to-set-legends-font-type) seems to solve your issue. – Flow Jul 06 '23 at 10:10

1 Answers1

0

You can try this one

import matplotlib.pyplot as plt

# Configure Matplotlib to use the desired font
plt.rcParams['font.family'] = 'SimSun'  # Replace 'SimSun' with the font name you installed

# Create a simple plot
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)

# Set labels with Chinese characters
plt.xlabel('曲线1')
plt.ylabel('曲线2')

# Show the plot
plt.show()
BugsCreator
  • 433
  • 3
  • 10