如何将 matplotlib 图旋转 90 度? [英] How can I rotate a matplotlib plot through 90 degrees?

查看:142
本文介绍了如何将 matplotlib 图旋转 90 度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 matplotlib 中创建了一个图形,其中包含三个子图,一个在左上象限,一个在右上象限,一个在右下象限.右上角的图包含一个二维图像,另外两个图分别是在 Y 轴和 X 轴上的投影.我想将左上象限子图逆时针旋转 90 度,以便该图的 x 轴沿着二维图的 y 轴.

I have created a figure in matplotlib which contains three subplots, one in the top left quadrant, one in the top right quadrant, and one in the bottom right quadrant. The top right figure contains a two-d image, and the other two plots are the projection onto the Y and X axis respectively. I'd like to rotate the top left quadrant subplot through 90deg counterclockwise, so that the x-axis of that plot lies along the y-axis of the 2-d plot.

对于子图,我意识到我可以翻转 x 和 y 数据,旋转轴标签,在左侧创建一个图标题等.但我希望找到一个可以旋转整个的调用,通过 90 度完成绘图.但是我找不到.

For the subplot, I realize I could flip the x and y data, rotate the axis labels, create a plot title on the left hand side, etc. But I was hoping to find a single call which would just rotate the whole, finished plot through 90deg. But I can't find one.

有没有简单的方法可以做到这一点?

Is there a simple way to do this?

推荐答案

许多函数的另一个有趣参数是 transform(不同于 orientationpivot 这个参数也可以用在例如 plot).

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

transform 参数允许您添加由 转换 对象.例如,这是旋转一些随机数据图的方式:

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 numpy
from matplotlib import pyplot, transforms

data = numpy.random.randn(100)

# first of all, the base transformation of the data points is needed
base = pyplot.gca().transData
rot = transforms.Affine2D().rotate_deg(90)

# define transformed line
line = 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.

我最近发现 transform 参数在使用 pyplot.scatter(和其他 PathCollections)时没有按预期工作.在这种情况下,您可能需要使用 offset_transform.有关如何设置 offset_transform 的更多信息,请参阅此答案.

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.

这篇关于如何将 matplotlib 图旋转 90 度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆