在macOS上使用Matplotlib时出现中文乱码问题,可以通过以下步骤解决:
- 
安装中文字体: 
 首先,确保你的系统中已经安装了支持中文的字体。可以使用以下命令查看系统中的字体:fc-list :lang=zh如果没有合适的中文字体,可以安装一个。比如,可以下载并安装SimHei字体(黑体)或STSong字体(宋体)。 
- 
配置Matplotlib使用中文字体: 
 需要在Matplotlib的配置文件中指定使用的中文字体。可以在脚本中动态设置,或者修改Matplotlib的默认配置文件。动态设置字体: 
 在你的Python脚本中加入以下代码:import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties # 设置字体 font_path = '/Library/Fonts/Songti.ttc' # 这里需要替换为你系统中的中文字体路径 my_font = FontProperties(fname=font_path) plt.plot([1, 2, 3], [4, 5, 6]) plt.title('标题', fontproperties=my_font) plt.xlabel('X轴', fontproperties=my_font) plt.ylabel('Y轴', fontproperties=my_font) plt.show()修改Matplotlib默认配置文件: 
 找到Matplotlib的配置文件路径,并编辑该文件:import matplotlib print(matplotlib.matplotlib_fname())这会输出Matplotlib配置文件的路径,通常是 ~/.matplotlib/matplotlibrc或者~/.config/matplotlib/matplotlibrc。打开该文件,找到并修改以下行:# 设置默认字体 font.family : sans-serif font.sans-serif : SimHei, STSong也可以直接在配置文件中设置字体路径: # 设置字体路径 font.sans-serif : /Library/Fonts/Songti.ttc
- 
处理负号问题: 
 如果出现负号显示不正确的问题,可以通过以下代码解决:import matplotlib as mpl mpl.rcParams['axes.unicode_minus'] = False
将以上步骤整合在一起,你的代码应该类似于:
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import matplotlib as mpl
# 设置字体路径
font_path = '/Library/Fonts/Songti.ttc'  # 替换为你系统中的中文字体路径
my_font = FontProperties(fname=font_path)
# 解决负号显示问题
mpl.rcParams['axes.unicode_minus'] = False
# 绘制图形
plt.plot([1, 2, 3], [4, 5, 6])
plt.title('标题', fontproperties=my_font)
plt.xlabel('X轴', fontproperties=my_font)
plt.ylabel('Y轴', fontproperties=my_font)
plt.show()这样就可以解决Matplotlib在macOS上显示中文乱码的问题。