Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the colors per value when coloring plots by a DataFrame column?

In matplotlib (in particular, pandas), how can I map specific colors to values of a column that I use for differentiating colors?

Let's say I have a column ...

>> df["country"]
DE
EN
US
DE

... and now I'd like to plot values from the DataFrame where each country is colored differently. How can I determine which country gets which color? With a colormap? I wasn't able to find the proper documentation, unfortunately.

I would like to apply a dict like this:

# pseudo-code
colormapping = {"DE": "blue", ...}
df.plot(colorby="country", colormapping)

Edit:

Here's a sample DataFrame.

    outlook   play  temperature country
0     sunny   True           25      DE
1     sunny   True           25      EN
2  overcast   True           19      DE
3      rain  False           21      US
4  overcast  False           33      IT
5      rain  False           27      EN
6      rain  False           22      FR
7  overcast   True           26      FR
8     sunny   True           13      FR
9     sunny   True           16      CH
like image 289
Xiphias Avatar asked Aug 17 '16 14:08

Xiphias


1 Answers

You can do so by specifying the dictionary mapping of hue levels to corresponding matplotlib colors in the palette argument of a categorical plot using seaborn as shown:

sns.set(style="whitegrid")
sns.swarmplot(x="outlook", y="temperature", hue="country", data=df, size=8,
              palette={'DE':'b', 'EN':'g', 'US':'r','IT':'c', 'FR':'y', 'CH':'k'})

enter image description here

like image 98
Nickil Maveli Avatar answered Sep 20 '22 22:09

Nickil Maveli