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

时间:2014-05-12 19:45:43

标签: python matplotlib plot subplot colorbar

我试图并排生成两个子图,共享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()

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

enter image description here

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

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

2 个答案:

答案 0 :(得分: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')

enter image description here

答案 1 :(得分:2)

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

enter image description here

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