Luke Polson
Luke Polson

Reputation: 444

Matplotlib Rotate xticklabels using ax.set()

Here's something I've been interested in for a while. We can obviously create a matplotlib plot and rotate the xticklabels like such.

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())

ax.set_title('Random Cumulative Sum')
ax.set_xlabel('Stages')
ax.set_xticks([0, 250, 500, 750, 1000])
ax.set_xticklabels(['one','two','three','four','five'],
                   rotation=30, fontsize='small')

Suppose I'd rather use a dictionary to accomplish this. I can make a (nearly) identical plot using

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())

props = {'title': 'Random Cumulative Sum',
        'xlabel': 'stages',
        'xticks': [0,250,500,750,1000],
        'xticklabels': ['one','two','three','four','five']}

ax.set(**props)

I have not specified that the xticklabels need to be rotated in the props dictionary. Is there a way to include this information in the dictionary?

Upvotes: 7

Views: 3296

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339260

Rotation is a property of the ticklabels, not the axes. You may use plt.setp to set the properties of any object(s).

props = {"rotation" : 30}
plt.setp(ax.get_xticklabels(), **props)

Upvotes: 11

Related Questions