I have gotten fairly proficient at combining my python dataframes with plotly , but this recent task has me stumped. I feed some state-level data into a USA map, and it renders beautifully. I have referred to links like this:
and
And after making some modifications - everything works as far as being able to change the column of the dataframe that provides the color value for each state. It even changes the range of the color scale , since the different columns have different ranges of values. However, the one part I haven’t gotten to work is using a different “continuous color scale”. No matter what I do, it just uses the default.
Here is my code - you will notice that I specify the argument, but it has no effect. I do know that its checking the color scale argument, because if I pass an invalid scale, like xxxx, I get an error. I have a feeling that I need to pass it on the update_layout, but I haven’t solved it. For this example, the data in the csv file doesnt matter, since my question just refers to the color scale being used on the map.
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
df = pd.read_csv("./states.csv")
cols_dd = ["Medicare", "Medicaid"]
fig = go.Figure()
for i, value in enumerate(cols_dd):
# use a different color axis for each trace... makes it more responsive
ca = f"coloraxis{i+2}"
figc = px.choropleth(
df,
locations="StateCode", # Spatial coordinates
color=value, # Data to be color-coded
color_continuous_scale="deep", # this value is not being honored, if I change it, the colors do not change
hover_name="StateCode",
scope="usa", locationmode = 'USA-states'
).update_traces(visible= True if value==cols_dd[0] else False
, coloraxis=ca
)
fig = fig.add_traces(figc.data)
fig.update_layout(title =f"<b>{cols_dd[0]}</b> ")
fig = fig.update_layout(
{
ca: {
"cmin": df[value].replace(0, np.nan).quantile(0.25),
"cmax": df[value].replace(0, np.nan).quantile(0.75),
"colorbar": {"title": value},
}
}
)
fig.update_layout( geo_scope='usa')
fig.update_layout(
updatemenus=[
{
"buttons": [
{
"label": f"{m}",
"method": "update",
"args": [
{
"visible": [
(m2 == m )
for m2 in cols_dd
]
},
{"title": f"<b>{m}</b> "},
],
}
for m in cols_dd
]
}
],
margin={"l": 0, "r": 0, "t": 25, "b": 0},
)