简体   繁体   English

Matplotlib:仅一个子图具有相等的长宽比

[英]Matplotlib: Equal aspect ratio for one subplot only

I would like to plot an image and along with traces along two of its axes. 我想绘制一个图像及其沿两个轴的轨迹。 I want shared axes (x for one trace and y for the other), no space between the plots but also an equal aspect ratio for the image. 我想要共享的轴(一条轨迹为x,另一条轨迹为y),各图之间没有空间,但图像的纵横比相等。 I work in Python 3.6. 我在Python 3.6中工作。

With GridSpec (I have also tried with subplots), I can accomplish the first part: 使用GridSpec(我也尝试过使用子图),可以完成第一部分:

没有空间

However, if I force an equal aspect ratio on the image, I get this 但是,如果我在图像上施加相等的长宽比,则会得到

在此处输入图片说明

It seems I cannot figure out how to have a square image with no spaces around... 看来我不知道如何制作一个方形图像,周围没有空格...

Here is the relevant part of my code (I also have a version using subplots): 这是我的代码的相关部分(我也有使用子图的版本):

    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')

Any help? 有什么帮助吗?

Maybe there's some clever way of avoiding this problem altogether, but as a quick solution you could just use subplots_adjust : 也许有某种巧妙的方法可以完全避免此问题,但是作为一种快速的解决方案,您可以使用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)

Though you'll want to alter the ticks somewhat, this gave me: 尽管您希望稍微改变刻度线,但这给了我:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM