matplotlib双向条形图调整yticks位置及移除xticks零值问题咨询
解决方案
1. 调整y轴刻度位置避免遮挡
你当前使用barh时指定了align='edge'且条形高度为0.3,每个条形的垂直覆盖范围是[索引值, 索引值+0.3],原yticks直接绑定索引值,刚好和条形边缘重叠。只需要给ytick位置增加0.15的偏移(即条形半高值),让刻度对齐条形中心,即可完全避开遮挡,不需要调整子图间距。
2. 移除x轴0刻度
遍历两个子图的x轴刻度,过滤掉值为0的项后重新设置即可。
修改后完整代码
import matplotlib.pyplot as plt import numpy as np fig, axes = plt.subplots(ncols=2, sharey=True, figsize=(12,12)) axes[0].barh(bar_chart.index, bar_chart['% Vaccinated'], align='edge', height=0.3, color='red', zorder=1) axes[0].set(title='% Fully Vaccinated') axes[1].barh(bar_chart.index, bar_chart['Deaths_Per_Confirmed_Case'], align='edge',height=0.3, color='pink', zorder=1) axes[1].set(title='% Deaths Per New Confirmed Cases') axes[0].invert_xaxis() # 改动1:给ytick位置加0.15偏移,对齐条形中心,可自行调整数值控制上下位移 axes[0].set(yticks=bar_chart.index + 0.15) axes[0].yaxis.tick_right() for ax in axes.flat: ax.margins(0.09) ax.grid(True) # 改动2:过滤掉x轴的0刻度 xticks = ax.get_xticks() ax.set_xticks(xticks[xticks != 0]) fig.tight_layout() fig.subplots_adjust(wspace=.06) plt.show()
补充说明
如果需要保留x轴的0刻度线但隐藏刻度标签,可以替换上面的过滤逻辑为:
ax.set_xticklabels(['' if x == 0 else x for x in ax.get_xticks()])
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

