Matplotlib Zh
Matplotlib does not display Chinese very well. To display Chinese in Matplotlib, we can use two methods:
* Set the font parameters of Matplotlib.
* Download and use a font library that supports Chinese.
Without setting the font, the default display is as follows, and the Chinese part cannot be displayed correctly:
!(#)
* * *
## Matplotlib Font Parameters
We can first get the list of system font libraries:
## Example
from matplotlib import pyplot as plt
import matplotlib
a=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for i in a:
print(i)
The output is similar to the following:
...Heiti TC HelveticaHelvetica NeueHerculanumHiragino Maru Gothic ProHiragino Mincho ProNHiragino SansHiragino Sans GB Hoefler Text...
The above code outputs all registered names in font_manager's ttflist. Find a Chinese font you like, such as: STFangsong (Fangsong), Heiti TC (Heiti), and then add the following code.
**For Windows:**
plt.rcParams['font.family'] = 'SimHei' # Replace with your chosen font
On Windows system, choose SimHei (Heiti) or other Chinese fonts, and set it as Matplotlib's default font.
**For Linux:**
plt.rcParams['font.family'] = 'WenQuanYi Micro Hei' # Replace with your chosen font
On Linux system, use fc-list command to view installed fonts, choose a Chinese font, and set it as Matplotlib's default font.
**For macOS:**
plt.rcParams['font.family'] = 'Heiti TC' # Replace with your chosen font
By setting plt.rcParams['font.family'], you tell Matplotlib to use the selected font to render text, so that Chinese can be displayed correctly in charts.
This way, you can use Chinese fonts supported by your system in Matplotlib charts.
## Example
import matplotlib.pyplot as plt
plt.rcParams['font.family']='Heiti TC'# Replace with your chosen font
# Create data
x =[1,2,3,4,5]
y =[2,4,6,8,10]
# Draw line chart
plt.plot(x, y)
# Add title and labels
plt.title('Line Chart Example')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
# Display the chart
plt.show()
Now Chinese can be displayed correctly, as shown below:
!(#)
Universal method for all platforms:
# -------------------------- Set Chinese font start -------------------------- plt.rcParams['font.sans-serif'] = [ # Windows priority 'SimHei', 'Microsoft YaHei', # macOS priority 'PingFang SC', 'Heiti TC', # Linux priority 'WenQuanYi Micro Hei', 'DejaVu Sans']# Fix the issue of minus sign displaying as a square plt.rcParams['axes.unicode_minus'] = False# -------------------------- Set Chinese font end --------------------------
## Example
import numpy as np
import matplotlib.pyplot as plt
# -------------------------- Set Chinese font start --------------------------
plt.rcParams['font.sans-serif']=[
# Windows priority
'SimHei','Microsoft YaHei',
# macOS priority
'PingFang SC','Heiti TC',
# Linux priority
'WenQuanYi Micro Hei','DejaVu Sans'
]
# Fix the issue of minus sign displaying as a square
plt.rcParams['axes.unicode_minus']=False
# -------------------------- Set Chinese font end --------------------------
# Generate simulated data: add some random noise based on sine curve
np.random.seed(42)
X = np.linspace(0,10,20)
y_true = np.sin(X)# True underlying pattern (we don't know)
y_noise = np.random.randn(20) * 0.3# Random noise
y = y_true + y_noise # Data we actually observe
plt.scatter(X, y, label='Observed Data (with noise)', color='blue', alpha=0.6)
plt.plot(X, y_true, label='True Pattern (y=sin(x))', color='green', linewidth=2)
plt.xlabel('X')
plt.ylabel('y')
plt.title('Data and Underlying Pattern')
plt.legend()
plt.grid(True)
plt.show()
Our goal is to find a curve (model) that best describes the pattern reflected by these blue scatter points (data).
The degree to which the model describes the data is called **fitting**.
* * *
## Using Font Library
By default, Matplotlib does not support Chinese. We can solve this using the following simple method.
Here we use Source Han Sans, an open-source font launched by Adobe and Google.
Official website: [https://source.typekit.com/source-han-serif/cn/](https://source.typekit.com/source-han-serif/cn/)
GitHub address: [https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese](https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese)
After opening the link, just choose one:
!(#)
You can also
YouTip