I am trying to set colour by different continent in Plotly. I am wondering on how to achieve this.
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.treemap(df, path=[px.Constant("world"), 'continent', 'country'], values='pop',
color='lifeExp', hover_data=['iso_alpha'],
color_continuous_scale=['#32a852', '#3261a8', '#a83259'],
color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.show()
Leaving heavy lifting to Plotly Express, once figure is built modify marker_color
list
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.treemap(
df,
path=[px.Constant("world"), "continent", "country"],
values="pop",
color="lifeExp",
hover_data=["iso_alpha"],
color_continuous_scale=["#32a852", "#3261a8", "#a83259"],
color_continuous_midpoint=np.average(df["lifeExp"], weights=df["pop"]),
)
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
cm = {
"Asia": "red",
"Africa": "yellow",
"Americas": "white",
"Europe": "blue",
"Oceania": "black",
}
fig.for_each_trace(
lambda t: t.update(
marker_colors=[
cm[id.split("/")[1]] if len(id.split("/")) == 2 else c
for c, id in zip(t.marker.colors, t.ids)
]
)
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments