未按需生成 Plotly 组

Plotly Groups not Being Generated as Needed

正在尝试绘制一些人口统计数据。此处的饼图将“19 岁以下”排在第二位,而它在索引中排在第一位。我想让情节变成“19 岁以下”、“20 - 44 岁”等。xaxis 中“类型”的使用不能解决我的问题。

问题情节:

剧情代码:

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

数据框:

我不知道如何停止使用 px 排序,但是如果你想用 go.Pie 替换 px.pie,我有一个解决方案。

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"]))])

之后您可以像往常一样更新您的布局并且您应该得到相同的结果但标签的顺序正确,因为排序现在设置为 false。如果您还想更改饼图的顺序,只需添加 direction='clockwise' 即可。

  • 我发现您的代码示例语法不正确。固定为仅使用 px
  • 解决方法很简单,加.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,
)