【问题标题】:How do I remove the x axis spacing between bars in a bar chart?如何删除条形图中条形之间的 x 轴间距?
【发布时间】:2023-03-24 14:25:01
【问题描述】:

在更改宽度以使条更小后,它已移到两侧。如何删除它们之间的间距。理想情况下,我想居中,但文档中似乎没有为它设置的参数。手动缩放图片也不会缩小这个差距。

import numpy as np
import matplotlib.pyplot as plt

objects = ('bar1', 'bar2')
y_pos = np.arange(len(objects))
performance = [2,6] 
stds=[0.3,0.5]
plt.bar(y_pos, performance, 0.3, align='center', yerr=stds,capsize=5, alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Time (seconds)')
plt.show()

【问题讨论】:

  • 使用plt.figure(1, figsize=(width, height)) 其中widthheight 表示以英寸为单位的图形大小,
  • @Flomp 不幸的是,即使使用极端值,差距仍然存在

标签: python matplotlib bar-chart


【解决方案1】:

List y_pos 将 bar 的位置设置为 0 和 1,然后设置宽度为 0.3,间隙为 0.7。

您必须将y_pos 替换为某些值以使您的条形彼此靠近:第一个条形必须位于width/2 位置,第二个位于1.5 * width 上。 然后您必须使用xlim 方法选择x 轴的最佳限制以使条居中。

import numpy as np
import matplotlib.pyplot as plt

objects = ('bar1', 'bar2')
w = 0.3
y_pos = (w/2.,w*1.5)
performance = [2,6] 
stds=[0.3,0.5]
plt.bar(y_pos, performance, width=w, align='center', yerr=stds,capsize=5, alpha=0.5)
plt.gca().set_xlim([-1.,1.5])
plt.xticks(y_pos, objects)
plt.ylabel('Time (seconds)')
plt.show()

我希望有更灵活和优雅的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多