python 中带有 barh 的 matplotlib

matplotlib with barh in python

我在 python 上的图表有问题。该图表似乎 set_xticklabels 的位置有误。请参见下图中的第二个图表。我怎样才能解决这个问题?我在这里提供代码。预先感谢您可能提供的任何帮助。

fig, (cx1, cx2) = plt.subplots(nrows=2, ncols=1, gridspec_kw={'height_ratios': [8, 8]}, figsize=(6, 10))
labels = 'A', 'B', 'C'
# Example data
y_pos = np.arange(len(labels))
performance1 = (nFX['FirstColumn'][n], nFX['SecondColumn'][n], nFX['ThirdColumn'][n])
performance2 = (nGX['FirstColumn'][n], nGX['SecondColumn'][n], nGX['ThirdColumn'][n])

labelsX12 = []
labelsX22 = []
maxX12 = max(nFX['FirstColumn'][n], nFX['SecondColumn'][n], nFX['ThirdColumn'][n])
minX12 = min(nFX['FirstColumn'][n], nFX['SecondColumn'][n], nFX['ThirdColumn'][n])
maxX22 = max(nGX['FirstColumn'][n], nGX['SecondColumn'][n], nGX['ThirdColumn'][n])
minX22 = min(nGX['FirstColumn'][n], nGX['SecondColumn'][n], nGX['ThirdColumn'][n])
for i in range(0,maxX12):
    if (i % 100) == 0:
        labelsX12.append(i)
        cx1.axvline(x=i)
for i in range(0,maxX22):
    if (i % 100) == 0:
        labelsX22.append(i)
        cx2.axvline(x=i)
    
cx1.barh(y_pos, performance1, align='center', zorder =3)    
cx1.set_yticks(y_pos)
cx1.set_yticklabels(labels, fontsize=20, fontname="Times New Roman")
cx1.invert_yaxis()  # labels read top-to-bottom
cx1.set_xticklabels(labelsX12, fontsize=20, fontname="Times New Roman")
cx1.set_xlabel('Number [#]', fontname="Times New Roman", fontsize=30)
cx1.set_title('1', fontsize=30, fontname="Times New Roman")

cx2.barh(y_pos, performance2, align='center', zorder =3)
cx2.set_yticks(y_pos)
cx2.set_yticklabels(labels, fontsize=20, fontname="Times New Roman")
cx2.invert_yaxis()  # labels read top-to-bottom
cx2.set_xticklabels(labelsX22, fontsize=20, fontname="Times New Roman")
cx2.set_xlabel('Number [#]', fontname="Times New Roman", fontsize=30)
cx2.set_title('2', fontsize=30, fontname="Times New Roman")

plt.tight_layout()

图表中的 xTick 多于您提供的标签。通过添加设置 xTicks:

cx1.set_xticks(labelsX12)
cx1.set_xticklabels(labelsX12, fontsize=20, fontname="Times New Roman")
...

cx2.set_xticks(labelsX22)
cx2.set_xticklabels(labelsX22, fontsize=20, fontname="Times New Roman")
...

这样您也可以摆脱与该行关联的 FixedFormatter 的警告。