4

I'd to plot a simple line plot but if I have more than 10 variables, plolty use the same color twice, how can I avoid it and always have a new color for a new variable ?

import pandas as pd
import numpy as np
pd.set_option("plotting.backend", "plotly")

df=pd.DataFrame(np.random.rand(100, 12)).cumsum()
df.plot()

Output:

enter image description here

vestland
  • 55,229
  • 37
  • 187
  • 305
PJP
  • 51
  • 4

3 Answers3

5

If you'd like to do this dynamically with regards to an arbitrary number of traces, you can sample a continuous plotly colorscale using px.colors.sample_colorscale() like this:

colors = px.colors.sample_colorscale("viridis", [n/(n_colors -1) for n in range(n_colors)])
df.plot(color_discrete_sequence=colors)

Plot 1 - 12 traces

enter image description here

Plot 2 - 50 traces

enter image description here

Complete code:

import pandas as pd
import numpy as np
import plotly.express as px
pd.set_option("plotting.backend", "plotly")

# data
df=pd.DataFrame(np.random.uniform(low=-2, high=2, size=(100,12))).cumsum()

# colors
n_colors = len(df.columns)
colors = px.colors.sample_colorscale("viridis", [n/(n_colors -1) for n in range(n_colors)])

# plot
df.plot(color_discrete_sequence=colors)
vestland
  • 55,229
  • 37
  • 187
  • 305
  • great, thanks, it's exactly what I needed – PJP Jan 21 '22 at 14:27
  • @PJP Great! And thanks for the feedback. Please consider marking my suggestion as the accepted answer. – vestland Jan 21 '22 at 16:25
  • Great solution! Is there a reason for the `n/(n_colors -1)`? I encountered a divide by zero on a DataFrame with a single column. Shouldn't `[n/n_colors for n in range(n_colors)])` work aswell? – Phonolog Jun 26 '23 at 07:58
0

You can pass a list of colors using the keyword colors like df.plot(colors=my_list).

Ich your list has as many colors as your DataFrame columns, the colors aren't repeaded.

Here is a example:

import pandas as pd
import numpy as np
import colorcet as cc

pd.set_option("plotting.backend", "matplotlib")
df=pd.DataFrame(np.random.rand(100, 12)).cumsum()
df.plot(color=cc.b_rainbow_bgyrm_35_85_c71[::15][:df.shape[0]])

Output

using 12 colors

mosc9575
  • 5,618
  • 2
  • 9
  • 32
0

Effectively it's documented here https://plotly.com/python/discrete-color/. You are using interface to plotly express

Code below using a different set of colors.

import pandas as pd
import numpy as np
pd.set_option("plotting.backend", "plotly")

df=pd.DataFrame(np.random.rand(100, 12)).cumsum()
color_seq = ['#AA0DFE',
 '#3283FE',
 '#85660D',
 '#782AB6',
 '#565656',
 '#1C8356',
 '#16FF32',
 '#F7E1A0',
 '#E2E2E2',
 '#1CBE4F',
 '#C4451C',
 '#DEA0FD',
 '#FE00FA',
 '#325A9B',
 '#FEAF16',
 '#F8A19F',
 '#90AD1C',
 '#F6222E',
 '#1CFFCE',
 '#2ED9FF',
 '#B10DA1',
 '#C075A6',
 '#FC1CBF',
 '#B00068',
 '#FBE426',
 '#FA0087']

df.plot(color_discrete_sequence=color_seq)


Rob Raymond
  • 29,118
  • 3
  • 14
  • 30