Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annoying white space in bar chart (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:

enter image description here

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

like image 831
user2983638 Avatar asked Nov 26 '13 10:11

user2983638


People also ask

How do I get rid of white space Matplotlib?

Hide the Whitespaces and Borders in Matplotlib Figure To get rid of whitespace around the border, we can set bbox_inches='tight' in the savefig() method. Similarly, to remove the white border around the image while we set pad_inches = 0 in the savefig() method.

How do I remove spaces between bars in Python?

To remove gaps between bars, we can change the align value to center in the argument of bar() method.

How do you change the space between bar graphs in Python?

The space between bars can be added by using rwidth parameter inside the “plt. hist()” function. This value specifies the width of the bar with respect to its default width and the value of rwidth cannot be greater than 1.

How do I reduce the bar size in Matplotlib?

To set width for bars in a Bar Plot using Matplotlib PyPlot API, call matplotlib. pyplot. bar() function, and pass required width value to width parameter of bar() function. The default value for width parameter is 0.8.


1 Answers

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:

no xlim

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:

with xlim

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

like image 63
dnf0 Avatar answered Oct 19 '22 23:10

dnf0