Reputation: 3794
If I create a plotly express figure like so:
fig = px.line(data, color_discrete_map={"Gold": "gold","Silver": "silver"})
,
it works fine.
But if I want to update the colors after the figure is created, like so:
fig = px.line(data)
fig.update_layout(color_discrete_map={"Gold": "gold", "Silver": "silver"})
I get
AttributeError: 'Figure' object has no attribute 'color'
I have also tried with update_traces()
with no success.
What is the correct way to do this please?
Upvotes: 0
Views: 683
Reputation: 520
When you create a figure with plotly.express, you receive a plotly.graph_objs figure. You can pass the parameter color_discrete_map, which is used in the constructor of the express figure to set the colors of the different lines, but afterwards you only can change them through their plotly.graph_objects properties.
It becomes a lot clearer when you do this:
fig1 = px.line(data, color_discrete_map={"Gold": "gold","Silver": "silver"})
fig2 = px.line(data)
print(fig1)
print(fig2)
You will have to change the line_color property of the respective line. A solution could be to do it somewhat like this:
import plotly.express as px
import pandas as pd
data = pd.DataFrame({"Gold":[1, 2, 3], "Silver":[2, 1, 3]})
fig = px.line(data)
colors = {"Gold":"gold", "Silver":"silver"}
for linename, linecolor in colors.items():
for figline in fig.data:
if figline.name == linename:
figline.line.color = linecolor
fig.show()
Upvotes: 1