【问题标题】:Matplotlib: Equal aspect ratio for one subplot onlyMatplotlib:仅一个子图的等宽比
【发布时间】:2019-03-13 15:29:27
【问题描述】:

我想绘制一个图像以及沿其两个轴的轨迹。我想要共享轴(一条迹线为 x,另一条迹线为 y),图之间没有空间,但图像的纵横比也相等。我在 Python 3.6 中工作。

使用 GridSpec(我也尝试过使用子图),我可以完成第一部分:

但是,如果我在图像上强制使用相等的纵横比,我会得到这个

似乎我无法弄清楚如何制作一个周围没有空格的方形图像......

这是我的代码的相关部分(我也有一个使用子图的版本):

    h, w = plt.figaspect(1)
    fig = plt.figure(figsize = (h, w))
    grid = fig.add_gridspec(nrows = 2, ncols = 2, 
              hspace = 0, wspace = 0, width_ratios = [2, 1], 
              height_ratios = [1, 2])
    ax = fig.add_subplot(grid[1,0])
    ay = fig.add_subplot(grid[0,0], sharex = ax)
    az = fig.add_subplot(grid[1,1], sharey = ax)
    plt.setp(ay.get_xticklabels(), visible = False)
    plt.setp(az.get_yticklabels(), visible = False)

    # Add this for square image
    ax.set_aspect('equal')

有什么帮助吗?

【问题讨论】:

    标签: python python-3.x matplotlib plot


    【解决方案1】:

    也许有一些巧妙的方法可以完全避免这个问题,但作为一种快速解决方案,您可以使用subplots_adjust

    import matplotlib.pyplot as plt
    
    h, w = plt.figaspect(1)
    fig = plt.figure(figsize = (h, w))
    grid = fig.add_gridspec(nrows = 2, ncols = 2, 
              hspace = 0, wspace = 0, width_ratios = [2, 1], 
              height_ratios = [1, 2])
    ax = fig.add_subplot(grid[1,0])
    ay = fig.add_subplot(grid[0,0], sharex = ax)
    az = fig.add_subplot(grid[1,1], sharey = ax)
    plt.setp(ay.get_xticklabels(), visible = False)
    plt.setp(az.get_yticklabels(), visible = False)
    
    # Add this for square image
    ax.set_aspect('equal')
    
    # Adjust subplots
    plt.subplots_adjust(top=0.9)
    

    虽然你会想稍微改变刻度,但这给了我:

    【讨论】:

    • 谢谢。这条简单的线就成功了,尽管我还必须更改“top”的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 2019-10-30
    • 2015-03-27
    • 1970-01-01
    相关资源
    最近更新 更多