在绘制颜色条时强制使用方形子图

问题描述 投票:1回答:2

我正在尝试并排生成两个子图,共享y轴,两个都有一个颜色条。

这是我的代码的MWE:

import matplotlib.pyplot as plt
import numpy as np

def rand_data(l, h):
    return np.random.uniform(low=l, high=h, size=(100,))

# Generate data.
x1, x2, y, z = rand_data(0., 1.), rand_data(100., 175.), \
rand_data(150., 200.), rand_data(15., 33.)

fig = plt.figure()
cm = plt.cm.get_cmap('RdYlBu')

ax0 = plt.subplot(121)
plt.scatter(x1, y, c=z, cmap=cm)

ax1 = plt.subplot(122)
# make these y tick labels invisible
plt.setp(ax1.get_yticklabels(), visible=False)
plt.scatter(x2, y, c=z, cmap=cm)

cbar = plt.colorbar()
plt.show()

返回的是左侧子图,水平比右侧略大,因为最后一个包含颜色条,见下图:

我尝试过使用ax.set_aspect('equal'),但由于x轴不在同一范围内,结果看起来很糟糕。

我需要将这两个图都显示为平方。我怎样才能做到这一点?

python matplotlib plot subplot colorbar
2个回答
5
投票

为了扩展我的评论,可以制作3个图,在第3个图中绘制colorbar(),在第1个和第2个图中绘制数据图。这样,如果有必要,我们可以自由地做任何我们想要的第一和第二个图:

def rand_data(l, h):
    return np.random.uniform(low=l, high=h, size=(100,))

# Generate data.
x1, x2, y, z = rand_data(0., 1.), rand_data(100., 175.), \
rand_data(150., 200.), rand_data(15., 33.)

fig = plt.figure(figsize=(12,6))
gs=gridspec.GridSpec(1,3, width_ratios=[4,4,0.2])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
cm = plt.cm.get_cmap('RdYlBu')
ax1.scatter(x1, y, c=z, cmap=cm)
SC=ax2.scatter(x2, y, c=z, cmap=cm)
plt.setp(ax2.get_yticklabels(), visible=False)
plt.colorbar(SC, cax=ax3)
plt.tight_layout()
plt.savefig('temp.png')


2
投票

更新 - 这是另一个不使用GridSpec的选项。

import numpy as np
import matplotlib.pyplot as plt

N = 50
x_vals = np.random.rand(N)
y_vals = np.random.rand(N)
z1_vals = np.random.rand(N)
z2_vals = np.random.rand(N)

minimum_z = min(np.min(z1_vals), np.min(z2_vals))
maximum_z = max(np.max(z1_vals), np.max(z2_vals))

fig, axis_array = plt.subplots(1,2, figsize = (20, 10), subplot_kw = {'aspect':1})
ax0 = axis_array[0].scatter(x_vals, y_vals, c = z1_vals, s = 100, cmap = 'rainbow', vmin = minimum_z, vmax = maximum_z)
ax1 = axis_array[1].scatter(x_vals, y_vals, c = z2_vals, s = 100, cmap = 'rainbow', vmin = minimum_z, vmax = maximum_z)

cax = fig.add_axes([0.95, 0.05, 0.02, 0.95]) #this locates the axis that is used for your colorbar. It is scaled 0 - 1. 
fig.colorbar(ax0, cax, orientation = 'vertical') #'ax0' tells it which plot to base the colors on

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.