18

How can I adjust the amount of space between the x-axis and the edge of the plot window? My x-axis labels are oriented vertically and they are running off of the edge of the window that Matplotlib draws.

Here's some example code:

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]
plt.plot(x,y)
plt.xticks(rotation='vertical')
plt.show()
thenickname
  • 6,684
  • 14
  • 41
  • 42

2 Answers2

18

As Paul said, you are using figures. You can get a reference to the current figure with gcf() and then set the spacing as per the FAQ. I've added two lines to your code:

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]
plt.plot(x,y)
plt.xticks(rotation='vertical')

fig = plt.gcf()
fig.subplots_adjust(bottom=0.2)

plt.show()
Daan
  • 2,049
  • 14
  • 21
  • 1
    Just applying `fig.tight_layout()` can solve this without any manual fiddling. – Dzamo Norton Oct 15 '19 at 12:20
  • 1
    Indeed, though tight_layout() did not yet exist when this question was asked. And apparently, eight years later, [tight_layout](https://matplotlib.org/3.1.1/tutorials/intermediate/tight_layout_guide.html) is still labelled as 'experimental' (however, I expect it to work well in most typical use cases, so your comment is a valuable addition to this answer). – Daan Oct 15 '19 at 14:53
3

Here's a solution in the FAQ entitled Move the edge of an axes to make room for tick labels.

Paul
  • 42,322
  • 15
  • 106
  • 123
  • I'm not using figures; it would greatly complicate my program to do so. – thenickname Feb 22 '11 at 15:59
  • @thenickname You are using figures. They are created automatically. They are just are not visible in the global scope. You can access these objects in a variety of ways. If you post some code, you'll get more specific answers on how to make adjustments to these figures as cleanly and simply as possible. – Paul Feb 22 '11 at 16:16
  • I've added some example code. I add various data sets to the plot in various loops throughout my program. Adding subplots would complicate things. – thenickname Feb 22 '11 at 16:48
  • Not very useful as websites change and we don't know where the link was pointing... – loco.loop Aug 11 '23 at 14:32