我还是不太确定;但我会试一试。对不起,如果我误解了。
主要想法是使用GridSpec 来解决您的两个要求:对齐“颜色轴”并将它们放在经典轴旁边。对齐应该是正确的,因为ax_x/ax_y 和主ax 之间的对应轴是相同的。
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb
from matplotlib.gridspec import GridSpec
import numpy as np
# Create a spectrum sample
# Convert HSV to RGB so that matplotlib can plot;
# hsv_to_rgb assumes values to be in range [0, 1]
N = 0.001
v_y, h_x = np.mgrid[0:1:N, 0:1:N]
c = hsv_to_rgb(np.stack([h_x, np.ones(h_x.shape), v_y], axis=2))
c_x = hsv_to_rgb(np.stack([h_x, np.ones(h_x.shape), np.zeros(v_y.shape)], axis=2))
c_y = hsv_to_rgb(np.stack([np.zeros(h_x.shape), np.ones(h_x.shape), v_y], axis=2))
fig = plt.figure()
# Ratio to adjust width for "x axis" and "y axis"
fig_ratio = np.divide(*fig.get_size_inches())
gs = GridSpec(2, 2, wspace=0.0, hspace=0.0,
width_ratios=[1, 20], height_ratios=[20/fig_ratio, 1])
# Lower-left corner is ignored
ax_y = plt.subplot(gs[0])
ax = plt.subplot(gs[1])
ax_x = plt.subplot(gs[3])
# Image are stretched to fit the ax since numbers are hided or not important in this figure.
img = ax.imshow(c, aspect='auto', origin='lower')
# Colorbar on img won't give correct results since it is plot with raw RGB values
img_x = ax_x.imshow(c_x, aspect='auto', origin='lower')
img_y = ax_y.imshow(c_y, aspect='auto', origin='lower')
# Remove ticks and ticklabels
for ax in [ax_y, ax, ax_x]:
ax.tick_params(left=False, bottom=False,
labelleft=False, labelbottom=False)
plt.show()
对评论的回应:
为了澄清,您正在制作三个图,并通过将它们分配给网格的象限来使用 imshow 图作为轴?
是的,它是一个 2x2 网格,我忽略了左下方的网格。文档可能不是很好,但我所做的类似于this part。
如果我想在这里的轴和主图之间添加空间,我会增加 wspace 和 hspace?
是的,它在文档的this part 中有简要说明。另外,我用width_ratios和height_ratios调整了它,使图形的3部分大小不一样,比如this。
另外,为了确认,这张图片的底部有一个全黑的轴,它不是左轴的错位。
底部是彩色的 x 轴。它是黑色的,因为我认为它对应于v=0。如果你改变了
c_x = hsv_to_rgb(np.stack([h_x, np.ones(h_x.shape), np.zeros(v_y.shape)], axis=2))
到
c_x = hsv_to_rgb(np.stack([h_x, np.ones(h_x.shape), np.ones(v_y.shape)], axis=2))
你会得到这个数字,证明它没有错位:
如果更简单,你也可以忽略整个 hsv 的东西,使用灰色框或其他东西作为中心图像。
对不起,我真的很慢。我仍然不知道你想在图中显示什么。所以我不知道如何帮助。如果您删除或注释掉该行
img = ax.imshow(c, aspect='auto', origin='lower')
你得到了这个: