【问题标题】:How can I rotate a matplotlib plot through 90 degrees?如何将 matplotlib 图旋转 90 度?
【发布时间】:2014-04-27 17:44:58
【问题描述】:

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

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

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

【问题讨论】:

    标签: python matplotlib rotation figure


    【解决方案1】:

    许多函数的另一个有趣参数是transform(与orientationpivot 不同,此参数也可以用于例如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,这也是此答案的灵感来源。


    更新

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

    【讨论】:

    • 我真的很喜欢这个答案——它对我帮助很大。请注意,总和的顺序很重要:rot + base != base + rot
    【解决方案2】:

    许多 pyplot 1D 绘图似乎在它们自己的参数中具有“方向”或“枢轴”选项。例如,来自 matplotlib.org 的直方图示例:

    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)
    

    只要改成水平(orientation=u'vertical'

    【讨论】:

    • 但是为什么matplotlib在绘图前要把坐标翻转90度
    【解决方案3】:
    from mpl_toolkits.mplot3d import axes3d
    import matplotlib.pyplot as plt
    
    fig=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()
    

    【讨论】:

    • 主代码:- ax.view_init(-30, -90)
    【解决方案4】:

    很简单:

    1. 交换散点数据的轴 (x, y):(y, x)。
    2. 将 y 的符号更改为负 (-y, x) 将图顺时针旋转 90 度,将 x 的符号更改为负 (y, -x) 将图逆时针旋转 90 度。详情在: https://www.tutorialguruji.com/python/rotate-plot-in-matplotlib-figure-by-90-degree/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 2012-12-23
      • 1970-01-01
      相关资源
      最近更新 更多