python柱状图标签重叠_pythonmatplotlib画盒图、⼦图解决坐
标轴标签重叠的问题
在使⽤matplotlib画图的时候将常会出现坐标轴的标签太长⽽出现重叠的现象,本⽂主要通过⾃⾝测过好⽤的解决办法进⾏展⽰,希望也能帮到⼤家,原图出现重叠现象例如图1:
代码为:
data1=[[0.3765,0.3765,0.3765,0.3765,0.3765],[0.3765,0.3765,0.3765,0.3765,0.3765],
[0.3765,0.3765,0.3765,0.3765,0.3765],[0.3765,0.3765,0.3765,0.3765,0.3765]]
data2=[[0.2985,0.2268,0.2985,0.2996,0.2985],[0.2022,0.3203,0.3141,0.2926,0.2681],
[0.2985,0.2668,0.2786,0.2985,0.2985],[0.2985,0.2985,0.2984,0.2978,0.2966]]
data3=[[0.7789,0.7698,0.6999,0.7789,0.7789],[0.7788,0.7758,0.7768,0.7698,0.8023],
[0.7789,0.7781,0.7789,0.7789,0.7789],[0.7789,0.7782,0.7752,0.7852,0.7654]]
data4=[[0.6688,0.6688,0.6688,0.6981,0.6618],[0.6688,0.5644,0.5769,0.5858,0.5882],
[0.6688,0.6688,0.6688,0.6688,0.6646],[0.6688,0.6646,0.6646,0.6688,0.6746]] #date1-date4均为我⽤到的数据,数据的形式等可⾃⾏更换。
##将4个图画在⼀张图上
fig=plt.figure(figsize=(13,11))
ax1=fig.add_subplot(2, 2, 1)##左右布局
ax2=fig.add_subplot(2, 2, 2)
ax3=fig.add_subplot(2, 2, 3)##上下布局
ax4=fig.add_subplot(2, 2, 4)
plt.sca(ax1)
labels=['Today is Sunday','Today is Monday','Today is Tuesday','Today is Wednesday']#标签
plt.boxplot(data1,labels=labels,boxprops={'linewidth':'2'},capprops={'linewidth':'2'},whiskerprops=
{'linewidth':'2'},medianprops={'linewidth':'2'}) #linewidth设置线条的粗细;boxprops、capprops、whiskerprops、medianprops表⽰盒图中各个线条的类型
plt.ylabel('Today',fontsize=16)
plt.xlabel('(a)',fontsize=16)
plt.sca(ax2)
labels=['Today is Sunday','Today is Monday','Today is Tuesday','Today is Wednesday']
plt.boxplot(data2,labels=labels,boxprops={'linewidth':'2'},capprops={'linewidth':'2'},whiskerprops=
{'linewidth':'2'},medianprops={'linewidth':'2'})
matplotlib中subplot
plt.xlabel('(b)',fontsize=16)
plt.sca(ax3)
labels=['Today is Sunday','Today is Monday','Today is Tuesday','Today is Wednesday']
plt.boxplot(data3,labels=labels,boxprops={'linewidth':'2'},capprops={'linewidth':'2'},whiskerprops=
{'linewidth':'2'},medianprops={'linewidth':'2'})
plt.ylabel('Today',fontsize=16)
plt.xlabel('(c)',fontsize=16)
plt.sca(ax4)
labels=['Today is Sunday','Today is Monday','Today is Tuesday','Today is Wednesday']
plt.boxplot(data4,labels=labels,boxprops={'linewidth':'2'},capprops={'linewidth':'2'},whiskerprops=
{'linewidth':'2'},medianprops={'linewidth':'2'})
plt.xlabel('(d)',fontsize=16)
plt.show()
1、解决办法1: 将轴标签分两⾏显⽰,如图2:
只需在原代码中每个⼦图画图中加上代码:
ax1.set_xticklabels(['Today is Sunday','\n'+'Today is Monday','Today is Tuesday','\n'+'Today is Wednesday'],fontsize=16)
'\n'+则表⽰换⾏显⽰的意思,想要哪个标签换⾏显⽰,则在标签前⾯加上此符号,也可以换多⾏,⼀个\n表⽰⼀⾏,例如'\n\n'+则表⽰换两⾏显⽰。fontsize是设置显⽰标签的字体⼤⼩。
2、解决办法2:轴标签倾斜显⽰
同样只需在原代码的基础上加上⼀句代码:
ax1.set_xticklabels(['Today is Sunday','Today is Monday','Today is Tuesday','Today is Wednesday'],fontsize=16,rotation=10)
rotation表⽰倾斜的⾓度,10即为倾斜10度,可任意设置,也可结合上⾯换⾏显⽰⼀同使⽤。
3、解决办法3:利⽤matplotlib⾥⾯的⾃动调整语句
只需在原代码的画图部分的最后加上matplotlib⾃动调整的语句,图则会⾃动调整标签⼤⼩:
plt.tight_layout()
以上这篇python matplotlib画盒图、⼦图解决坐标轴标签重叠的问题就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持脚本之家。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。