How to hide (or show) some of plotly colors

Question:

I have simple dataframe with 3 plots:

import plotly.express as px
import pandas         as pd
import numpy          as np

N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5

df_all = pd.DataFrame()

df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y0
df['type'] = np.full(len(random_x), 0)
df_all = pd.concat([df_all, df], axis=0)

df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y1
df['type'] = np.full(len(random_x), 1)
df_all = pd.concat([df_all, df], axis=0)


df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y2
df['type'] = np.full(len(random_x), 2)
df_all = pd.concat([df_all, df], axis=0)


fig = px.line(x=df_all['x'], y=df_all['y'], color=df_all['type'])
fig.show()

enter image description here

  • Is there a way to show the figure and by default choose which colors to show (or which colors to hide) ? (i.e show only colors 0 and 1) ?
  • Can we do it without changing the dataframe, but rather change the plotly settings ?
Asked By: user3668129

||

Answers:

You can iterate over fig.data and edit the Scatter objects. Setting the visible property to "legendonly" will achieve what you need.

Hiding "1" for instance:

import plotly.express as px
import pandas         as pd
import numpy          as np

N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5

df_all = pd.DataFrame()

df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y0
df['type'] = np.full(len(random_x), 0)
df_all = pd.concat([df_all, df], axis=0)

df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y1
df['type'] = np.full(len(random_x), 1)
df_all = pd.concat([df_all, df], axis=0)


df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y2
df['type'] = np.full(len(random_x), 2)
df_all = pd.concat([df_all, df], axis=0)


fig = px.line(x=df_all['x'], y=df_all['y'], color=df_all['type'])

for scat in fig.data:
    if scat.legendgroup == "1":
        scat.visible = "legendonly"

fig.show()
Answered By: Tranbi