Lamps1829
Lamps1829

Reputation: 2451

preventing x axis labels from getting chopped in matplotlib/pyplot

With sufficient rotation, the labels of my bar chart's columns get chopped off. Here's an example that should illustrate what happens:

import matplotlib.pyplot as plt

x = [1,2,3]
y = [2,3,4]
s = ['long_label_000000000','long_label_000000001','long_label_000000002']
plt.bar(x,y)
plt.xticks(range(len(s)),s, rotation=90)
plt.show()

I know that doing the following will cause the graphs to be adjusted automatically in accordance with the canvas size:

from matplotlib import rcParams 
rcParams.update({'figure.autolayout':True})

However, this adjusts the height of the graph to accommodate the labels (including producing a squashed-looking graph if the labels are large enough), and I'd rather maintain uniform graph dimensions.

Can anyone recommend a way to just extend the bottom of the canvas if the labels are getting chopped? Thanks.

Upvotes: 2

Views: 1896

Answers (1)

Schorsch
Schorsch

Reputation: 7905

You can control your figure size using figsize=(w,h) when initializing a figure. In addtion you can manually control your axis location with a subplot and subplots_adjust:

w = 12 # width in inch
h = 12 # height in inch

fig = plt.figure(figsize=(w,h))

ax = fig.add_subplot(111)
plt.subplots_adjust(bottom=0.25)

x = [1,2,3]
y = [2,3,4]
s = ['long_label_000000000','long_label_000000001','long_label_000000002']
ax.bar(x,y)
ax.set_xticks(range(len(s)))
ax.set_xticklabels(s,rotation=90)
plt.show()

Upvotes: 2

Related Questions