Search code examples
pythonplotlypie-chartplotly-pythonplotly-express

Plotly express order label with a pie chart


Let's take this sample dataframe :

df = pd.DataFrame({"Day":['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
'Proportion':[0.24495486, 0.17300189, 0.23019185, 0.15408692, 0.17827757,0.01100911, 0.0084778]})

         Day  Proportion
0     Monday    0.244955
1    Tuesday    0.173002
2  Wednesday    0.230192
3   Thursday    0.154087
4     Friday    0.178278
5   Saturday    0.011009
6     Sunday    0.008478

I would like to use plotly express to visualize this dataframe through a pie chart. I've built the following function :

import plotly.express as px

def plot_pie_graph(df_graph,col_names,col_values, title_x = "axis_x",title_y="axis_y",title = "Graphe",
                   color_discrete_map = {}, save_graph_name = "") :
    
    if title_x == "axis_x" :
        title_x = col_names
    if title_y == "axis_y":
        title_y = col_values
    
    fig = px.pie(df_graph, values = col_values, names = col_names,color_discrete_map=color_discrete_map,
                 color=col_names)

    fig.update_layout({
            'plot_bgcolor': 'rgba(0,0,0,0)',
            'paper_bgcolor': 'rgba(0,0,0,0)',
        },
        hoverlabel=dict(
            #bgcolor="white", 
            font_size=12, 
            #font_family="Rockwell"
        ),
        xaxis={
            'title': title_x,
            },
        yaxis={'title':title_y},
        title={
            'text': title,
            #'y':0.95,
            'x':0.5,
            'xanchor': 'center',
            'yanchor': 'top'},
        hovermode = "x"
    )
    
    if save_graph_name != "" :
        fig.write_html(save_graph_name + ".html")
    
    fig.show()

And when I use it, I got the following pie chart :

plot_pie_graph(df,"Day",'Proportion',title = "Proportion by day")

enter image description here

Days are not ordered as in the dataframe. I saw that there is a parameter called "category_order" with bar charts to deal with this issue but not available with pie charts. How please could I logically order the days in the label ?


Solution

  • Just add

    fig.update_traces(sort=False) 
    

    after you create the figure and before you save/show the figure.