Python matplotlib cannot display Chinese, missing fonts (Mac)

The solution that Python cannot display Chinese fonts using Matplotlib drawing - Programmer Sought

Error:

/Applications/anaconda3/lib/python3.9/site-packages/IPython/core/pylabtools.py:151: UserWarning: Glyph 33457 (\N{CJK UNIFIED IDEOGRAPH-82B1}) missing from current font.

The font setting of Mac OS is different from that of Win. It is useless to download SimHei according to the general process and put it in the corresponding directory.

First enter the following command in Jupyter to view the list of fonts in matplotlib:

#查询一下matplotlib中拥有哪些语言
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)
    
#Heiti TC
#Songti SC

After screening, it is found that matplotlib in Mac contains two Chinese fonts, Heiti TC and Songti SC.

Enter the following command to set the font and test the effect:

import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc("font", family='Heiti TC')
 
squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth=3)
#设置图表标题并给坐标轴加上标签。
ax.set_title("主题", size=14)
ax.set_xlabel("横坐标", size=14) # color='red'
ax.set_ylabel("纵坐标", size=14) # color='red'
 
ax.tick_params(axis='both', labelsize=14)
plt.show()

 I found that the effect is very good, just use it as a template to solve other problems.

Guess you like

Origin blog.csdn.net/qq_51314244/article/details/130131655