简体   繁体   中英

How to make a multi-color seaborn lineplot in python

I have a dictionary with key value pairs:

COLORS= {'fish':'blue','tigers':'orange'}

and data:

  team  value  
0 fish   20
1 fish   15
2 fish   10
3 tigers 7
4 tigers 13
5 tigers 15

I would like to make a lineplot and use the .get() method to get the color of each team and color the line plot accordingly (first three half of the line would be blue, last half orange)

I tried using the following code:

sns.lineplot(data = df, x = np.arange(len(df)), y = value, color=COLORS.get(df.team)

But I get the error


TypeError: 'Series' objects are mutable, thus they cannot be hashed

I can get it to work with the following code

...color=COLORS[df.team.iloc[0]]

But that makes the whole lineplot the first color that appears, which in this case would be blue. Again, I want to color the lineplot according to team , and I am not sure why .get() isn't working. Any ideas?

.get() doesn't work because you are calling it on a dictionary object but passing pandas.Series object.

It will work if you pass a single value that you are searching for. ( See this article if you need further explanation )
Which you did by passing COLORS[df.team.iloc[0]] but it only passes a single value ie the first team and that's why you get the whole plot in one color.

I would group DataFrame by team, then iterate over grouped DataFrame and draw a new line for each team. Now you can use .get() function on COLORS dictionary and get correct color.

See if this helps you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM