Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
Luke Polson Avatar asked Aug 07 '18 11:08

Luke Polson


People also ask

How do I rotate Xticks in MatPlotLib?

MatPlotLib with Python To rotate tick labels in a subplot, we can use set_xticklabels() or set_yticklabels() with rotation argument in the method. Create a list of numbers (x) that can be used to tick the axes. Get the axis using subplot() that helps to add a subplot to the current figure.

How do you rotate an AXE in Python?

MatPlotLib with PythonMake a tuple of axes extremes. Add a mutable 2D affine transformation, "t". Add a rotation (in degrees) to this transform in place. Add a transform from the source (curved) coordinate to target (rectilinear) coordinate.

How do you rotate an Xticklabel?

Set xticks label rotation at 90 degrees by using plt. yticks() method and set rotation= 90 as the argument in the method. Finally, display the figure by using the plt. show() method.


1 Answers

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)
like image 75
ImportanceOfBeingErnest Avatar answered Nov 14 '22 22:11

ImportanceOfBeingErnest