python用matplotlib作图的时候,中文标注无法正常显示,乱码为小方框的解决办法

12 篇文章 0 订阅
3 篇文章 0 订阅

关于python引用matplotlib作图的时候,中文标注无法正常显示,乱码为小方框
通常在作图的时候,没有设置字体以为是默认字体,但是这里会追踪不到字体的位置,运行下面的代码,出现的图会出现不能显示中文的异常

from matplotlib import pyplot as plt
import random

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize=(20,8), dpi=80)

plt.plot(x,y)

x_label =list(x)
x_label_show = ["10点{}分".format(i) for i in range(60)]
x_label_show += ["11点{}分".format(i-60) for i in range(60,120)]
plt.xticks(x_label[::3],x_label_show[::3],rotation=-90)  # rotation旋转的度数
plt.show()

图像的结果:
这里写图片描述

解决办法:
代码中添加如下信息

# windows 和linux设置字体的方法
# import matplotlib

# font = {'family' : 'MicroSoft YaHei',
#         'weight' : 'bold',
#         'size'   : 10}
# matplotlib.rc("font", **font)

# 通用字体设置
from matplotlib import font_manager

# my_font = font_manager.FontProperties(fname="字体的本地完整路径")
my_font = font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")
......
plt.xticks(......, fontproperties=my_font)  # rotation旋转的度数

实例完整代码如下:

from matplotlib import pyplot as plt
import random


# windows 和linux设置字体的方法
# import matplotlib

# font = {'family' : 'MicroSoft YaHei',
#         'weight' : 'bold',
#         'size'   : 10}
# matplotlib.rc("font", **font)

# 通用字体设置
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")


x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize=(20,8), dpi=80)

plt.plot(x,y)

x_label =list(x)
x_label_show = ["10点{}分".format(i) for i in range(60)]
x_label_show += ["11点{}分".format(i-60) for i in range(60,120)]
plt.xticks(x_label[::3],x_label_show[::3],rotation=-90, fontproperties=my_font)  # rotation旋转的度数
plt.show()

实例效果:
这里写图片描述

另外,遇到图例p l t.legend()要展示中文的时候,此时得换用方法plt.legend(prop=my_font)
实例:

# 统计从11岁到30岁每年交的男(女)朋友数量
from matplotlib import pyplot as plt
from matplotlib import font_manager

y_0 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_1 = [1,0,3,1,2,2,3,3,2,1,2,1,1,1,1,1,1,1,1,1]

x=range(11,31)

my_font = font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)
plt.plot(x,y_0,label="自己")
plt.plot(x,y_1,label="同桌")

# 设置x轴刻度
xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,xtick_labels,fontproperties=my_font)
plt.yticks(range(0,9))

# 绘制网格
plt.grid(alpha=0.2)  # alpha 透明度

# 添加图例
plt.legend(prop=my_font, loc="upper right")  # prop:设置字体; loc:设置展示的位置,upper left 左对齐,upper right 右对齐


# 展示
plt.show()

在这里插入图片描述
搞定~

  • 10
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kungs8

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值