循环后将颜色条添加到散点图

时间:2020-07-09 10:27:11

标签: python matplotlib seaborn

我正在尝试向连续的散点图添加连续的颜色条(类似于答案herehere中的答案)。出于我的目的,我正在使用循环构建散点图,然后尝试添加连续的颜色条,但是我不知道要包含哪个对象作为fig.colorbar()的参数。你会怎么做?

import pandas as pd
import seaborn as sb
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)

df=pd.DataFrame(np.random.rand(2, 100), index=['S1','S2']).T
tars=np.random.choice([0,0.3,0.5,0.8,1], 100)
df=pd.concat([df,pd.Series(tars, name='group')],1)
colors = matplotlib.cm.viridis(np.linspace(0,1,len(pd.unique(tars))))

fig = plt.figure(figsize = (10,8), dpi=300)
ax = fig.add_subplot(1,1,1) 
targets=pd.unique(tars)
for target, color in zip(targets,colors):
    ...
    g=ax.scatter(
        df.loc[df.group==target, 'S1'], 
        df.loc[df.group==target, 'S2'],
        color = [color]
    )
fig.colorbar(g)
plt.show()

enter image description here

如果我添加ax.legend(targets)而不是fig.colorbar(g),则图例正确显示,但属于分类。

df=pd.DataFrame(np.random.rand(2, 100), index=['S1','S2']).T
tars=np.random.choice([0,0.3,0.5,0.8,1], 100)
df=pd.concat([df,pd.Series(tars, name='group')],1)

cmap=matplotlib.cm.gnuplot2
colors = cmap(np.linspace(0,1,len(pd.unique(tars))))

fig = plt.figure(figsize = (10,8), dpi=300)
ax = fig.add_subplot(1,1,1) 
targets=pd.unique(tars)
for target, color in zip(targets,colors):
    ...
    g=ax.scatter(
        df.loc[df.group==target, 'S1'], 
        df.loc[df.group==target, 'S2'],
        color = [color]
    )
ax.legend(targets)
plt.show()

enter image description here

2 个答案:

答案 0 :(得分:0)

我不确定是否要完全了解for循环。

这是您正在寻找的输出吗?

fig = plt.figure()
ax = fig.add_subplot(1,1,1) 
g = ax.scatter(df['S1'],df['S2'],c=df['group'],cmap='viridis')
cbar = fig.colorbar(g)
plt.show()

enter image description here

答案 1 :(得分:0)

感谢to this answer,我可以编辑代码以显示连续的颜色条。

df=pd.DataFrame(np.random.rand(2, 100), index=['S1','S2']).T
tars=np.random.choice([0,0.3,0.5,0.8,1], 100)
df=pd.concat([df,pd.Series(tars, name='group')],1)

cmap=matplotlib.cm.viridis
colors = cmap(np.linspace(0,1,len(pd.unique(tars))))

fig = plt.figure(figsize = (10,8), dpi=300)
ax = fig.add_subplot(1,1,1) 
targets=pd.unique(tars)
for target, color in zip(targets,colors):
    g=ax.scatter(
        df.loc[df.group==target, 'S1'], 
        df.loc[df.group==target, 'S2'],
        color=[color]
    )

norm = plt.Normalize(np.min(tars), np.max(tars))
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
ax.figure.colorbar(sm)
plt.show()

enter image description here