Matplotlib,具有共享颜色条的多个散点图

alk*_*key 5 python matplotlib

我正在尝试创建一组散点图,并希望它们共享相同的颜色条。

我遵循了此处的指导但它似乎仅适用于绘制对象具有自动缩放属性的图像。

我使用的代码如下:

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()
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

AttributeError: 'AxesSubplot' 对象没有属性 'autoscale_None'

当我将数据发送到这里的颜色栏时,问题发生了:

f.colorbar(axes[0][0], cax=cbar_ax)
Run Code Online (Sandbox Code Playgroud)

这是当前输出,显然我希望标记的颜色位于右侧的比例尺上(我会担心以后正确放置它):

在此处输入图片说明

对于像这样的一组散点图,是否有办法实现这一点,如果是这样,我该如何修改我的代码来实现它?

Imp*_*est 8

的签名figure.colorbar

colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)
Run Code Online (Sandbox Code Playgroud)

这意味着第一个参数必须是 ScalarMappable,而不是轴。

sc = axes[0][0].scatter(..)
fig.colorbar(sc, cax=cbar_ax)
Run Code Online (Sandbox Code Playgroud)

如果您想对所有散点图使用相同的颜色条,则需要对所有散点图使用相同的标准化。

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)
Run Code Online (Sandbox Code Playgroud)

一个完整的例子:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述