简体   繁体   English

python matplotlib和子图大小的问题

[英]Issues with python matplotlib and subplot sizes

I am trying to create a figure with 6 sub-plots in python but I am having a problem. 我试图在python中创建一个包含6个子图的图,但我遇到了问题。 Here is a simplified version of my code: 这是我的代码的简化版本:

import matplotlib.pyplot as plt
import numpy

g_width = 200
g_height = 200
data = numpy.zeros(g_width*g_height).reshape(g_height,g_width)

ax1 = plt.subplot(231)
im1 = ax1.imshow(data)
ax2 = plt.subplot(232)
im2 = ax2.imshow(data)
ax3 = plt.subplot(233)
im3 = ax3.imshow(data)
ax0 = plt.subplot(234)
im0 = ax0.imshow(data)
ax4 = plt.subplot(235)
im4 = ax4.imshow(data)
ax5 = plt.subplot(236)
ax5.plot([1,2], [1,2])
plt.show()

The above figure has 5 "imshow-based" sub-plots and one simple-data-based sub-plot. 上图有5个“基于imshow的”子图和一个基于简单数据的子图。 Can someone explain to me why the box of the last sub-plot does not have the same size with the other sub-plots? 有人可以向我解释为什么最后一个子图的框与其他子图的大小不同? If I replace the last sub-plot with an "imshow-based" sub-plot the problem disappears. 如果我用“基于imshow的”子图替换最后一个子图,问题就会消失。 Why is this happening? 为什么会这样? How can I fix it? 我该如何解决?

The aspect ratio is set to "equal" for the 5 imshow() calls (check by calling ax1.get_aspect() ) while for ax5 it is set to auto which gives you the non-square shape you observe. I'm guessing "equal" for the 5 imshow() calls (check by calling ,纵横比设置为"equal" for the 5 calls (check by calling ax1.get_aspect()进行calls (check by calling ) while for ax5, it is set to auto which gives you the non-square shape you observe. I'm guessing which gives you the non-square shape you observe. I'm guessing imshow()` defaults to equal while plot does not. which gives you the non-square shape you observe. I'm guessing imshow()`默认为相等,而情节没有。

To fix this set all the axis aspect ratios manually eg when creating the plot ax5 = plt.subplot(236, aspect="equal") 要手动修复此设置所有轴纵横比,例如创建绘图时ax5 = plt.subplot(236, aspect="equal")

On a side node if your creating many axis like this you may find this useful: 在侧节点上,如果您创建这样的多个轴,您可能会发现这很有用:

fig, ax = plt.subplots(ncols=3, nrows=2, subplot_kw={'aspect':'equal'})

Then ax is a tuple (in this case ax = ((ax1, ax2, ax3), (ax4, ax5, ax6)) ) so to plot in the i , j plot just call 然后ax是一个元组(在这种情况下ax = ((ax1, ax2, ax3), (ax4, ax5, ax6)) )所以要绘制在ij图中只是调用

ax[i,j].plot(..)

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

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