簡體   English   中英

如何在 python 中制作多色 seaborn 線圖

[英]How to make a multi-color seaborn lineplot in python

我有一個帶有鍵值對的字典:

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()方法獲取每個團隊的顏色並相應地為線 plot 着色(線的前三半為藍色,后半為橙色)

我嘗試使用以下代碼:

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為 lineplot 着色,我不確定為什么.get()不起作用。 有任何想法嗎?

.get()不起作用,因為您在dictionary object 上調用它,但傳遞pandas.Series object。

如果您傳遞要搜索的單個值,它將起作用。 (如果您需要進一步解釋,請參閱這篇文章
您通過傳遞COLORS[df.team.iloc[0]]完成了該操作,但它只傳遞了一個值,即第一個團隊,這就是為什么您以一種顏色獲得整個 plot 的原因。

我將按團隊對 DataFrame 進行分組,然后遍歷分組的 DataFrame 並為每個團隊繪制一條新線。 現在您可以在COLORS字典上使用.get() function 並獲得正確的顏色。

看看這是否對您有幫助:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM