How to Change the X Axis in Matplotlib So There Is No White Space

How can I change the x axis in matplotlib so there is no white space?

There is an automatic margin set at the edges, which ensures the data to be nicely fitting within the axis spines. In this case such a margin is probably desired on the y axis. By default it is set to 0.05 in units of axis span.

To set the margin to 0 on the x axis, use

plt.margins(x=0)

or

ax.margins(x=0)

depending on the context. Also see the documentation.

In case you want to get rid of the margin in the whole script, you can use

plt.rcParams['axes.xmargin'] = 0

at the beginning of your script (same for y of course). If you want to get rid of the margin entirely and forever, you might want to change the according line in the matplotlib rc file:

axes.xmargin : 0
axes.ymargin : 0

Example

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
tips.plot(ax=ax1, title='Default Margin')
tips.plot(ax=ax2, title='Margins: x=0')
ax2.margins(x=0)

Sample Image


Alternatively, use plt.xlim(..) or ax.set_xlim(..) to manually set the limits of the axes such that there is no white space left.

How to remove axis, legends, and white padding

The axis('off') method resolves one of the problems more succinctly than separately changing each axis and border. It still leaves the white space around the border however. Adding bbox_inches='tight' to the savefig command almost gets you there; you can see in the example below that the white space left is much smaller, but still present.

Newer versions of matplotlib may require bbox_inches=0 instead of the string 'tight' (via @episodeyang and @kadrach)

from numpy import random
import matplotlib.pyplot as plt

data = random.random((5,5))
img = plt.imshow(data, interpolation='nearest')
img.set_cmap('hot')
plt.axis('off')
plt.savefig("test.png", bbox_inches='tight')

Sample Image

Matplotlib tight_layout -- remove extra white/empty space

You can remove the x and y axis and then use savefig with bbox_inches='tight' and pad_inches = 0 to remove the white space. See code below:

plt.axis('off') # this rows the rectangular frame 
ax.get_xaxis().set_visible(False) # this removes the ticks and numbers for x axis
ax.get_yaxis().set_visible(False) # this removes the ticks and numbers for y axis
plt.savefig('test.png', bbox_inches='tight',pad_inches = 0, dpi = 200).

This will result in

Sample Image

In addition, you can optionally add plt.margins(0.1) to make the scatter points not touch the y axis.

Removing white space around a saved image

I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file.
(Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)

plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)

I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.

Remove the space in x axis because of no value

The easiest solution is not to use the "Day" as the x-value but only for the labeling. The values are just consecutive values (np.arange(...)):

Covox_Call = pd.DataFrame()

Covox_Call["Day"] = [1,3,4]
Covox_Call["Cumilative Contacted"] = [31,111,156]
Covox_Call["Not Contacted"] = [688,608,563]

x=np.arange(Covox_Call["Day"].shape[0])
y_1=Covox_Call["Cumilative Contacted"]
y_2=Covox_Call["Not Contacted"]
plt.bar(x,+y_1,label="Contacted")
plt.bar(x,-y_2,label="Not Contacted")
plt.xticks(x, Covox_Call["Day"])

Sample Image

How to set space between the axis and the label

You can set bounding by using labelpad argument like this

ax.set_ylabel('Y', rotation=0, labelpad=10)

also you can add space after 'Y ' label in set_ylabel line as following

ax.set_ylabel('Y ',rotation=0)

Note:

As you mentioned you want the same spaces between both axis labels so you can set 'X' label using:

 ax.text(max(x)/2, -(max(y)/10),'X')

and

'Y' label using:

 ax.text(-(max(x)/10), max(y)/2,'Y')

Editing bounds to get rid of white-space within a plot in matplotlib

You can use the various pyplot functions called xlim, ylim (to set the limits of the axes), xticks, yticks (to set the tick positions) etc. Read the documentation.



Related Topics



Leave a reply



Submit