Plotly Groups not Being Generated as Needed

Trying to plot out some demographic data. The pie chart here puts "Under 19" second when it is first in the index. I would like to for the plot to go "Under 19", "20 - 44", etc. The usage of "type" in the xaxis does not solve my issue.

Plot of Issue: enter image description here

Code for the plot:

fig = go.Figure(data = px.pie(cur_state_data,
                                  values=87,
                                  color='index',
                                  names='index',
                                  color_discrete_sequence=["#97af97",'#C49330',"#31443c","#c15f3d",],))
fig.update_layout(font_family="Courier",
                      title={'text':'Proportions',
                             'font': {'size': 15}},
                      hovermode=False,)
                      # xaxis={'type':'category'})
fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=True)
fig.update_yaxes(showline=True, linewidth=1, linecolor='black', mirror=True)
age_plot = fig.to_html(full_html=False, default_height=300, default_width=400,config = {'displayModeBar': False})

DataFrame:

Demographics Data DF


Solution 1:

  • I found your code sample syntax to be incorrect. Fixed to just use px
  • solution is simple, just add .update_traces(sort=False)
import pandas as pd
import numpy as np
import plotly.express as px

cur_state_data = pd.DataFrame(
    index=["Under 19", "20 - 44", "45 - 64", "65 and Up"],
    data=np.array([[34.8, 36.7, 19.7, 8.8], [32.8, 36.6, 19.7, 10.7]]).T,
    columns=[86, 87],
)

fig = px.pie(
    cur_state_data,
    values=87,
    color=cur_state_data.index,
    names=cur_state_data.index,
    color_discrete_sequence=[
        "#97af97",
        "#C49330",
        "#31443c",
        "#c15f3d",
    ],
).update_traces(sort=False)
fig.update_layout(
    font_family="Courier",
    title={"text": "Proportions", "font": {"size": 15}},
    hovermode=False,
)

enter image description here

Solution 2:

I couldn't figure out how to stop sorting with px, but if you want to replace px.pie with go.Pie, I have a solution.

fig = go.Figure(data=[go.Pie(labels=cur_state_data['index'],
                                 values=cur_state_data[87],
                                 sort=False,
                                 marker=dict(colors=["#97af97", '#C49330', "#31443c", "#c15f3d"]))])

After that you can update your layout as usual and you should get the same result but with labels in the correct order, since sort is now set to false. If you also want to change the order of the pie pieces just add direction='clockwise' to it.