Xiphias Xiphias - 2 months ago 4x
Python Question

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"]

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


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


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.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