如何解决如何将高度和宽度子图轴与gridspec和matplotlib对齐?
我正在尝试使用matplotlib with gridspec创建一个子图,使轴的排列看起来类似于下图;该图取自this unrelated question。
下面是我重新创建此轴排列的尝试。 具体地说,我的问题是轴未正确对齐。例如,蓝色直方图的轴对象比具有各种绿色阴影的图像的轴对象高;橙色直方图似乎可以按照宽度正确对齐,但是我将其归因于运气。 如何正确对齐这些轴?与原始图不同,我想在轴之间添加/填充额外的空白空间,以使边框不相交;下面代码中的切片符号通过添加空白行/列来实现。 (为了不使帖子的长度超出必须的长度,我没有通过玩轴刻度等来使数字“漂亮”。)
与原始图片不同,轴未完全对齐。有没有一种方法可以使用约束布局不执行此操作?我是说fig,ax = plt.subplots(constrained_layout=True)
的派生词?
下面是用于重现我的身材的MWE代码;请注意,ax.imshow(...)
和ax.matshow(...)
之间没有区别。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
## initialize figure and axes
fig = plt.figure()
gs = fig.add_gridspec(6,6,hspace=0.2,wspace=0.2)
ax_bottom = fig.add_subplot(gs[4:,2:])
ax_left = fig.add_subplot(gs[:4,:2])
ax_big = fig.add_subplot(gs[:4,2:])
## generate data
x = np.random.normal(loc=50,scale=10,size=100)
y = np.random.normal(loc=500,scale=50,size=100)
## get singular histograms
x_counts,x_edges = np.histogram(x,bins=np.arange(0,101,5))
y_counts,y_edges = np.histogram(y,1001,25))
x_mids = (x_edges[1:] + x_edges[:-1]) / 2
y_mids = (y_edges[1:] + y_edges[:-1]) / 2
## get meshed histogram
sample = np.array([x,y]).T
xy_counts,xy_edges = np.histogramdd(sample,bins=(x_edges,y_edges))
## subplot histogram of x
ax_bottom.bar(x_mids,x_counts,width=np.diff(x_edges),color='darkorange')
ax_bottom.set_xlim([x_edges[0],x_edges[-1]])
ax_bottom.set_ylim([0,np.max(x_counts)])
## subplot histogram of y
ax_left.bar(y_mids,y_counts,width=np.diff(y_edges),color='steelblue')
ax_left.set_xlim([y_edges[0],y_edges[-1]])
ax_left.set_ylim([0,np.max(y_counts)])
## subplot histogram of xy-mesh
ax_big.imshow(xy_counts,cmap='Greens',norm=Normalize(vmin=np.min(xy_counts),vmax=np.max(xy_counts)),interpolation='nearest',origin='upper')
plt.show()
plt.close(fig)
编辑:
可以通过在每行/列中显式设置width_ratios
和height_ratios
来初始化轴;如下所示。这不会影响输出,但是也许我使用不正确?
## initialize figure and axes
fig = plt.figure()
gs = gridspec.GridSpec(ncols=6,nrows=6,figure=fig,width_ratios=[1]*6,height_ratios=[1]*6)
ax_bottom = fig.add_subplot(gs[4:,2:])
解决方法
问题出在n
上,它会自动调整轴的大小以保持正方形像素的外观。
您可以通过以下方式防止这种情况发生:
imshow
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。