为什么python制作图表空白,条形图中的烦人空白(matplotlib,Python)

It's probably a trivial question, but I am trying to plot a bar chart with matplotlib and with rotated text on the x axis.

The code I'm using is shown below:

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")

It works perfectly, but I obtain an annoying white space on the right of the x axis, as shown by the red ellipse in the following picture:

08e3b004c18fdfe938a11381bcacf6bd.png

Do you know how I can remove it? Thanks in advance!

解决方案

Try calling plt.xlim() with the number of bins, e.g.

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

Here is an example:

#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()

No plt.xlim() output:

1bbaeff341ffe37678f5015e510fa2b8.png

Now plot it with plt.xlim using the number of bins to define the size:

#plot it

ax = plt.subplot(111)

ax.bar(bin, data, width, color='r')

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

plt.show()

Results it:

a20472f69df0a640aab0720fb7287b16.png

There may be a better way, but this should work for you.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值