【问题标题】:Annoying white space in bar chart (matplotlib, Python)条形图中令人讨厌的空白(matplotlib,Python)
【发布时间】:2013-12-11 10:39:03
【问题描述】:

这可能是一个微不足道的问题,但我正在尝试使用 matplotlib 和 x 轴上的旋转文本绘制条形图。 我正在使用的代码如下所示:

fig = plt.figure()

x_labels_list = []

for i in range(0, pow(2, N)):
    x_labels_list.append(str(f(i)))  # The function f() converts i to a binary string

ax = plt.subplot(111)
width = 1.0
bins = map(lambda x: x-width, range(1,pow(2,N)+1))
ax.bar(bins, my_data, width=width)
ax.set_xticks(map(lambda x: x-width/2, range(1,pow(2,N)+1)))
ax.set_xticklabels(x_labels_list, rotation=90, rotation_mode="anchor", ha="right")

效果很好,但是我在 x 轴的右侧得到了一个恼人的空白,如下图的红色椭圆所示:

你知道我怎样才能删除它吗?提前致谢!

【问题讨论】:

  • 你能发布一个复制你展示的数字的工作示例吗?

标签: python matplotlib bar-chart


【解决方案1】:

尝试使用垃圾箱数调用plt.xlim(),例如

plt.xlim([0,bins.size])

这是一个例子:

#make some data
N = 22
data = np.random.randint(1,10,N)
bin = np.arange(N)  
width = 1

#plot it
ax = plt.subplot(111)
ax.bar(bin, data, width, color='r')
plt.show()

没有plt.xlim() 输出:

现在用 plt.xlim 绘制它,使用 bin 的数量来定义大小:

#plot it
ax = plt.subplot(111)
ax.bar(bin, data, width, color='r')
plt.xlim([0,bin.size])
plt.show()

结果:

可能有更好的方法,但这应该适合你。

【讨论】:

  • 您也可以使用plt.axis('tight') 来完成同样的事情,而不必担心指定垃圾箱的数量。此外,如果您希望在边缘留出一点空间,请使用plt.margins(0.05, 0) 在 x 方向上填充 5% 的数据范围和在 y 方向上填充 0% 的数据范围。
  • @Joe Kington:是的,我也尝试过你的解决方案,它有效!
猜你喜欢
  • 2012-09-02
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多