【问题标题】:matplotlib with barh in pythonpython中带有barh的matplotlib
【发布时间】:2021-05-21 19:12:02
【问题描述】:

我在 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()

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    图表中的 xTicks 比您提供的标签多。通过添加来设置 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 的警告。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2019-01-30
      • 2012-09-26
      • 1970-01-01
      • 2020-08-18
      • 2016-05-15
      • 1970-01-01
      相关资源
      最近更新 更多