variable with spaces in plotly

I know it is not ideal to have variable names with spaces. But I am curious if there is a way to do this for plotly in python easily.

So this worked for variables without spaces:

fig_gender = px.bar(
    df_gender_grp, y="gender", x="index", 
    color="gender",
    labels=dict(gender="gender", index="count"),

but the same approach for variables with spaces (e.g., age group) did not work:

fig_age_grp = px.bar(
   df_age_grp, y="gender", x="index", 
   color="age group",
   labels=dict(df_age_grp.(age group)="age group", index="count")

I tried using the f-string as well as df.variable name approaches, but both did not work. The error message is "SyntaxError: invalid syntax"

Thank you.

>Solution :

In labels=... you map column names of your dataframe to text to be displayed in the legend or at the axes.

In your case, it seems that you want column age group to displayed as text age group (which would happen anyway) and column index to be displayed as count.

Try:

labels={"age group": "age group", "index": "count"}

Leave a Reply