【发布时间】:2020-10-29 22:14:07
【问题描述】:
我正在尝试向 seaborn 散点图添加一个连续的颜色条(类似于here 和here 中的答案)。出于我的目的,我正在使用循环构建散点图,然后尝试添加连续颜色条,但我不知道要包含哪个对象作为 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()
如果我添加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()
【问题讨论】:
-
您的示例中的点是它们应该看起来的样子,还是只是为了显示您想要颜色条的位置?由于点的颜色不是来自颜色条的颜色图。我最近遇到了一个类似的问题,我需要一个颜色条来表示使用不同颜色图比例的点集。这也是你需要的吗?
-
@FranciscaConcha-Ramírez 感谢您的评论。这些点实际上是正确的,但不是颜色条。我已经编辑了我的帖子以使其更清晰。
-
感谢您的澄清。我认为这个答案可能会有所帮助:stackoverflow.com/a/14779462/2943652
-
非常抱歉。这是对另一个问题的回应。我删了。
-
@FranciscaConcha-Ramírez 再看一遍,我注意到这些点按预期显示,但不是真的。我搞砸了并显示了固定代码的屏幕截图,但在我的问题中将 cmets 保留在已编辑的代码块中。我很抱歉,你问这个问题是对的。我现在已经按原样编辑了我的问题。我保留了屏幕截图,因为它们在质量上与我得到的相同
标签: python matplotlib seaborn