我在 matplotlib 中创建了一个图形,其中包含三个子图,一个在左上象限,一个在右上象限,一个在右下象限。右上图包含一个二维图像,另外两个图分别是在 Y 轴和 X 轴上的投影。我想将左上象限子图逆时针旋转 90 度,以便该图的 x 轴位于二维图的 y 轴上。
对于子图,我意识到我可以翻转 x 和 y 数据、旋转轴标签、在左侧创建绘图标题等。但我希望找到一个可以旋转整个图的调用, 通过 90deg 完成绘图。但是我找不到。
有没有简单的方法可以做到这一点?
最佳答案
许多函数的另一个有趣参数是transform
(与orientation
或pivot
不同,此参数也可用于例如plot
。 ).
transform
参数允许您添加由 Transform
指定的转换目的。举个例子,这是你如何旋转一些随机数据的图:
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()
有关如何旋转补丁的示例,请参阅 this answer ,这也是这个答案的灵感来源。
更新
我最近发现,在使用 pyplot.scatter
(和其他 PathCollections
)时,transform
参数无法按预期工作。在这种情况下,您可能希望使用 offset_transform
。参见 this answer有关如何设置 offset_transform
的更多信息。
关于python - 如何将 matplotlib 图旋转 90 度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22540449/