用饼图绘制表达订单标签

问题描述 投票:0回答:3

让我们看一下这个示例数据框:

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

我想使用plotlyexpress通过饼图可视化这个数据框。我构建了以下功能:

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()

当我使用它时,我得到了以下饼图:

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

enter image description here

天数的排序与数据框中的不同。我看到有一个名为“category_order”的参数,带有条形图来处理这个问题,但不适用于饼图。我怎样才能逻辑地对标签中的日期进行排序?

python plotly pie-chart plotly-python plotly-express
3个回答
8
投票

fig.update_traces(sort=False)

创建图形之后、保存/显示图形之前。


0
投票

go.Pie(labels=x, values=y, sort=False)



0
投票
https://plotly.com/python/styling-plotly-express/

饼图是逆时针添加的,但从 12 点钟开始,所以使用类似:

category_orders: dict[str, list[str]] = {"Day":['Monday','Tuesday','Wednesday','Thursday','Friday','Saterday','Sunday'] } fig = px.pie(df_graph, category_orders = category_orders, values = col_values, names = col_names,color_discrete_map=color_discrete_map, color=col_names)

	
© www.soinside.com 2019 - 2024. All rights reserved.