我有一本包含键值对的字典:
COLORS= {'fish':'blue','tigers':'orange'}和数据:
team value
0 fish 20
1 fish 15
2 fish 10
3 tigers 7
4 tigers 13
5 tigers 15我想做一个线条图,并使用.get()方法得到每个团队的颜色,并相应地给线条图涂上颜色(前三条线是蓝色的,最后一半是橙色的)
我尝试使用以下代码:
sns.lineplot(data = df, x = np.arange(len(df)), y = value, color=COLORS.get(df.team)但我明白错误
TypeError: 'Series' objects are mutable, thus they cannot be hashed我可以让它使用下面的代码
...color=COLORS[df.team.iloc[0]]但这使得整个线条图成为出现的第一种颜色,在这种情况下,它将是蓝色的。同样,我想根据team对线条图进行着色,我不知道为什么.get()不能工作。有什么想法吗?
发布于 2020-12-16 20:38:16
.get()无法工作,因为您是在dictionary对象上调用它,而是传递pandas.Series对象。
如果您传递要搜索的单个值,它将工作。(如果需要进一步解释,请参阅此文章 )
这是通过传递COLORS[df.team.iloc[0]]来实现的,但是它只传递一个值,即第一组,这就是为什么您在一种颜色中获得整个情节的原因。
我会按团队对DataFrame进行分组,然后迭代分组DataFrame并为每个团队画一条新的线。现在您可以在.get()字典上使用COLORS函数并获得正确的颜色。
看看这是否对你有帮助:
df = pd.DataFrame(data=data)
gk = df.groupby("team")
x = np.arange(len(df))
index = 0
for team_name, team_group in gk:
sns.lineplot(
x=x[index : index + len(team_group)],
y=team_group.value,
color=COLORS.get(team_name),
)
index += len(team_group)
plt.show()https://stackoverflow.com/questions/65329041
复制相似问题