Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seaborn cycle through colours with matplotlib scatter

How can I get seaborn colors when doing a scatter plot?

import matplotlib.pyplot as plt import seaborn as sns ax=fig.add_subplot(111) for f in files:     ax.scatter(args) # all datasets end up same colour     #plt.plot(args) #  cycles through palette correctly 
like image 699
amn41 Avatar asked Feb 10 '15 11:02

amn41


People also ask

How do you change the color of a scatterplot in seaborn?

Scatterplot with Seaborn Default Colors In addition to these arguments we can use hue and specify we want to color the data points based on another grouping variable. This will produce points with different colors. g =sns. scatterplot(x="gdpPercap", y="lifeExp", hue="continent", data=gapminder); g.

Can you use Matplotlib to create a colored scatterplot?

Matplotlib scatter plot color label To create a scatter plot, we use the scatter() method. To add a legend to a plot, we use the legend() method. To set the color of the legend, we pass facecolor parameter to the method.


2 Answers

You have to tell matplotlib which color to use. To Use, for example, seaborn's default color palette:

import matplotlib.pyplot as plt import seaborn as sns import itertools ax=fig.add_subplot(111)  palette = itertools.cycle(sns.color_palette())  for f in files:     ax.scatter(args, color=next(palette)) 

The itertools.cycle makes sure we don't run out of colors and start with the first one again after using the last one.

Update:

As per @Iceflower's comment, creating a custom color palette via

palette = sns.color_palette(None, len(files)) 

might be a better solution. The difference is that my original answer at the top iterates through the default colors as often as it has to, whereas this solution creates a palette with as much hues as there are files. That means that no color is repeated, but the difference between colors might be very subtle.

like image 50
Carsten Avatar answered Sep 23 '22 21:09

Carsten


To build on Carsten's answer, if you have a large number of categories to assign colours to, you might wish to zip the colours to a very large seaborn palette, for example the xkcd_palette or crayon_palette.. Note that this practice is usually a chartjunk anti-pattern: using more than 5-6 colours is usually overkill, and you might need to consider changing your chart type.

import matplotlib.pyplot as plt import seaborn as sns  palette = zip(df['category'].unique(), sns.crayons.values()) 
like image 35
François Leblanc Avatar answered Sep 20 '22 21:09

François Leblanc