0

I have a seaborn KDE plot but I am struggling to change the colormap. Even if I change the palatte it still remains Set1, even if palatte is changed to Blues or a different palatte color. How might I change the line plots to have the colors in colormap viridis? Also the code is in reference to this question and very helpful answer: Histogram of 2D arrays and determine array which contains highest and lowest values

import seaborn as sns
import pandas as pd


np.random.seed(1234)
array_2d = np.random.random((5, 20))

sns.kdeplot(data=pd.DataFrame(array_2d.T, columns=range(1, 6)), palette='Set1', multiple='layer')
plt.show()

But when I try changing the colormap I keep getting the error:

cmap = sns.color_palette("viridis", as_cmap=True)

sns.kdeplot(data=pd.DataFrame(array_2d.T, columns=range(1, 6)),cmap=cmap, multiple='layer')
plt.show()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_216114/3245378387.py in <module>
      1 cmap = sns.color_palette("viridis", as_cmap=True)
      2 
----> 3 sns.kdeplot(data=pd.DataFrame(array_2d.T, columns=range(1, 6)),cmap=cmap, multiple='layer')
      4 plt.show()

AttributeError: 'Line2D' object has no property 'cmap'

How do I change the line colors to a different color via the viridis or another colormap?

wabash
  • 779
  • 5
  • 21

1 Answers1

1

IIUC, using set_palette:

sns.set_palette('viridis')
sns.kdeplot(data=pd.DataFrame(array_2d.T, columns=range(1, 6)),  multiple='layer')

Output:

enter image description here

EDIT:

As pointed out by JohanC, simply pass palette='viridis' to kdeplot.

Or palette=list(plt.cm.viridis(np.linspace(0, 1, 5))).

BigBen
  • 46,229
  • 7
  • 24
  • 40
  • Thank you! :) Is there a way to set the colors for each line in the plot? for example, something along the lines of `linspace` and then calling the viridis color palatte? – wabash May 04 '22 at 15:01