我正在尝试创建一组散点子图,并希望它们共享相同的颜色条。
我已遵循指导 here但它似乎只适用于绘制对象具有自动缩放属性的图像。
我使用的代码如下:
import matplotlib.pyplot as plt
import numpy
import random
x = []
y = []
for i in range(100):
x.append(random.normalvariate(100,10))
y.append(random.normalvariate(100,10))
#Creates a list of length n
def getRand(n):
l = []
for i in range(n):
l.append(random.normalvariate(1,10))
return l
f = plt.figure()
f, axes = plt.subplots(nrows = 2, ncols = 2, sharex=True, sharey = True)
axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = "x")
axes[0][0].set_xlabel('Crosses', labelpad = 5)
axes[0][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 'o')
axes[0][1].set_xlabel('Circles', labelpad = 5)
axes[1][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = '*')
axes[1][0].set_xlabel('Stars')
axes[1][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 's' )
axes[1][1].set_xlabel('Squares')
#Add separate colourbar axes
cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7])
#Autoscale none
f.colorbar(axes[0][0], cax=cbar_ax)
plt.show()
这会产生错误:
AttributeError: 'AxesSubplot' 对象没有属性 'autoscale_None'
当我将数据发送到此处的颜色条时出现问题:
f.colorbar(axes[0][0], cax=cbar_ax)
这是当前的输出,显然我希望标记的颜色位于右侧的比例尺上(稍后我会担心是否正确放置):
对于像这样的一组散点图,是否可以实现这一目标?如果可以,我该如何修改我的代码来实现它?
最佳答案
figure.colorbar
的签名是
colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)
这意味着第一个参数必须是 ScalarMappable,而不是轴。
sc = axes[0][0].scatter(..)
fig.colorbar(sc, cax=cbar_ax)
如果您想对所有散点图使用相同的颜色条,则需要对它们全部使用相同的归一化。
norm=plt.Normalize(-22,22)
sc = axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), norm=norm)
fig.colorbar(sc, cax=cbar_ax)
一个完整的例子:
import matplotlib.pyplot as plt
import numpy as np
def getRand(n):
return np.random.normal(scale=10, size=n)
f = plt.figure()
f, axes = plt.subplots(nrows = 2, ncols = 2, sharex=True, sharey = True)
norm=plt.Normalize(-22,22)
sc = axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = "x", norm=norm)
axes[0][0].set_xlabel('Crosses', labelpad = 5)
axes[0][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 'o', norm=norm)
axes[0][1].set_xlabel('Circles', labelpad = 5)
axes[1][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = '*', norm=norm)
axes[1][0].set_xlabel('Stars')
axes[1][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 's', norm=norm )
axes[1][1].set_xlabel('Squares')
cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7])
f.colorbar(sc, cax=cbar_ax)
plt.show()
关于python - Matplotlib,具有共享颜色条的多个散点子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44970881/