'How to set color per column with Plotly

So simple and yet i just can't find solution after reading a lot. I would like to plot 2 columns out of my dataframe (Pandas) and i want to set color for each.

color_dic = {"Close":'#565454',"MA":"red"}
fig = data.plot(x=data.index,y=["Close","MA"],template="simple_white",color=color_dic)

Which is not the way to do so, but what would be an equivalent way to get this ?

Also , how can i add a scatter on top of this with a different color ?



Solution 1:[1]

there are many possibilities to plot with plotly, but if you use graphObject you can do:

import pandas as pd
import plotly.graph_objects as go
import plotly

data={"Close":[1,2,3,2,1,2,3,4],"MA":[0,1,2,3,4,5,2,1]}

df=pd.DataFrame(data)

fig = go.Figure()

color_dic = {"Close":'#565454',"MA":"red"}
# Add traces
for col in df.columns:
    fig.add_trace(go.Scatter(x=df.index, y=df[col],
                    mode='lines+markers',
                    name=col,
                    marker_color=color_dic[col]))

result: enter image description here

Solution 2:[2]

You can do this in many ways, and you can take a look at Plotly: How to define colors in a figure using plotly.graph_objects and plotly.express? for some details. But since you're specifically asking how to assign a color to a trace by the name of the source data in a pandas dataframe, I would use color_discrete_map = color_dict , where color_dict is a dictionary that contains {"Close":'#565454',"MA":"red"}, like this:

fig = df.plot(x=df.index,y=["Close","MA"],template="simple_white",
              color_discrete_map = color_dict)

Plot 1:

enter image description here

To include another trace, I would use fig.update_trace along with the trace type of choice like this:

fig.add_trace(go.Scatter(x=df.index, y=df['Close']*2,
                         mode = 'lines',
                         line_color = 'blue'))

Plot 2:

enter image description here

Complete code:

import numpy as np
import pandas as pd
pd.options.plotting.backend = "plotly"

df = pd.DataFrame({"Close":[1,2,3,4,5,8,7,8],"MA":[2,2,2,3,4,4,6,7]})
color_dict = {"Close":'#565454',"MA":"red"}

fig = df.plot(x=df.index,y=["Close","MA"],template="simple_white",
               color_discrete_map = color_dict)

fig.add_trace(go.Scatter(x=df.index, y=df['Close']*2,
                         mode = 'lines',
                         line_color = 'blue'))

fig.show()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Renaud
Solution 2