画图无法显示中文解决代码
import matplotlib.pyplot as plt
import matplotlib
# 设置matplotlib正常显示中文和负号
matplotlib.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
matplotlib.rcParams['axes.unicode_minus']=False # 正常显示负号
设置画板代码
# 设置大小,下列代码意思为900像素点长,350个像素点高
plt.figure(figsize=(9, 3.5))
设置X、Y轴代码
倾斜
# x轴的字体倾斜70°
plt.xticks(rotation=70)
# y轴的字体倾斜70°
plt.yticks(rotation=70)
大小
# x轴
plt.xticks(fontsize=13)
# and
plt.yticks(fontsize=13)
设置标签(label)代码
显示label、调整大小
# 显示label
plt.legend()
# 如果需要调整label的大小,则如下
plt.legend(fontsize=14)
# 如果需要调整label的位置
plt.legend('upper right')
# legend(loc='String' or Number, bbox_to_anchor=(num1, num2))
# 位置有如下:
# upper right, upper left, lower left, lower right, center
# right, center left, center right, lower center, upper center
双Y轴图问题
# 这里就不生成数据了
# 创建画板
fig = plt.figure(figsize=(9, 3.5))
# 左边的Y轴
ax1 = fig.add_subplot(111)
ax1.plot(x, data, '1', c='orangered', label='左边的')
plt.xticks(rotation=70, fontsize=13)
plt.yticks(fontsize=13)
# 右边的Y轴
ax2 = ax1.twinx()
ax2.plot(data2, '-D', label='右边的')
plt.yticks(fontsize=13)
# 这里的legend位置需要自己后面细调,调bbox_to_anchor里的参数
fig.legend(loc='upper left', fontsize=14, bbox_to_anchor=(0.13,0.88))
ax1.set_xlabel('xxx', fontsize=14)
ax1.set_ylabel('xxx', fontsize=14)
ax2.set_ylabel('xxx', fontsize=14)
plt.show()
给某个部分加背景色的代码(axvspan)
# axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)
# 第一个参数为起始位置,第二参数为结束位置,同样可以设置Y轴的上色位置
plt.axvspan(x[0], x[3], color='#EEB32A', alpha=0.3)
在图中写文字
这里借鉴了这篇文章
https://blog.csdn.net/TeFuirnever/article/details/88947248
plt.text(x,
y,
string,
fontsize=15,
verticalalignment="top",
horizontalalignment="right"
)
# x,y:表示坐标值上的值
# string:表示说明文字
# fontsize:表示字体大小
# verticalalignment:垂直对齐方式 ,参数:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
# horizontalalignment:水平对齐方式 ,参数:[ ‘center’ | ‘right’ | ‘left’ ]
# 例子
plt.text(x[0], y=10, '这里是文字', fontsize=16)
此文章作为自己记录,更新时间20230510