python中matplotlib作图时plt.legend()中无法显示中文,乱码为小方框

第一个

引入模块:
from matplotlib import font_manager

定义一个变量:
font = font_manager.FontProperties(fname = ‘电脑中字体的路径’)
然后再调用plt.legend(prop = font)

import matplotlib.pyplot as plt
from matplotlib import font_manager	 #matplotlib中 中文设置模块
import numpy as np

#中文字体路径(先看好自己电脑中的路径)
font = font_manager.FontProperties(fname = 'C:/Windows/fonts/simkai.ttf')

arr = np.genfromtxt('F:/Program Files/JetBrains/PycharmProjects/untitled/dat.csv', delimiter=',')
x_labels = np.array(['01.02', '01.03', '01.06', '01.07', '01.08', '01.09', '01.10', '01.13'])
x_arr = np.arange(len(arr[:,0]))

plt.bar(x_arr,arr[:,0],tick_label = x_labels,label = '百度')
plt.bar(x_arr,arr[:,1],bottom = arr[:,0],tick_label = x_labels,label = '阿里')
plt.bar(x_arr,arr[:,2],bottom = arr[:,1],tick_label = x_labels,label = '腾讯')

plt.legend(prop = font,loc = 'best')		#记得添加prop = font
plt.show()

第二个

当全部文字显示不出来时:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']    # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False    # 用来显示负号


===========或者==============
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

#打印本地中的所有字体
for font in fm.fontManager.ttflist:
  print(font.name)

plt.rcParams['font.family']=['SimHei']

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值