How can I rotate a matplotlib plot through 90 degrees? How can I rotate a matplotlib plot through 90 degrees? python python

How can I rotate a matplotlib plot through 90 degrees?


Many of the pyplot 1D plots seem to have "orientation" or "pivot" options within their own arguments. For example, from matplotlib.org example of histogram:

matplotlib.pyplot.hist(x,                        bins=10,                        range=None,                        normed=False,                        weights=None,                        cumulative=False,                        bottom=None,                        histtype=u'bar',                        align=u'mid',                        orientation=u'vertical',                        rwidth=None,                        log=False,                        color=None,                        label=None,                        stacked=False,                        hold=None,                        **kwargs)

Just change to horizontal (orientation=u'vertical')


Another interesting parameter for a lot of functions is transform (unlike orientation or pivot this parameter can also be used in e.g. plot).

The transform parameter allows you to add a transformation, specified by a Transform object. For the sake of example, this is how you would rotate the plot of some random data:

import numpyfrom matplotlib import pyplot, transformsdata = numpy.random.randn(100)# first of all, the base transformation of the data points is neededbase = pyplot.gca().transDatarot = transforms.Affine2D().rotate_deg(90)# define transformed lineline = pyplot.plot(data, 'r--', transform= rot + base)# or alternatively, use:# line.set_transform(rot + base)pyplot.show()

For an example on how to rotate a patch, see this answer, which was also the source of inspiration for this answer.


update

I recently found out that the transform parameter does not work as expected when using pyplot.scatter (and other PathCollections). In this case, you might want to use the offset_transform. See this answer for more information on how to the offset_transform can be set.


from mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as pltfig=plt.figure() ax=fig.add_subplot(111,projection='3d')# for rotate the axes and update.for angle in range(0,360):     ax.view_init(30,angle)plt.show()