【问题标题】:How to add 2dp to Plotly Go Sunburst如何将 2dp 添加到 Plotly Go Sunburst
【发布时间】:2021-08-17 05:30:39
【问题描述】:

此任务的目标:
1) 绘制分层旭日形图(年份 -> 产品类别 -> 产品子类别)
2) 标签显示百分比为 1/2 d.p.
3)基于总销售额的连续色标

我最初使用 Plotly Express 创建旭日形,但我意识到图表中显示的百分比总和不等于 100%,如下所示 (33 + 33 + 30 + 5 = 101%) Plotly express sunburst chart

然后我尝试使用 Plotly Go 绘制旭日形图,我首先定义了一个函数来创建数据框,然后使用新创建的 df 绘制旭日形图。该功能工作正常,但我不知道为什么该数字不显示。我被困住了。

功能代码:

levels = ['prod_subcat', 'prod_cat', 'year'] # levels used for the hierarchical chart
#color_columns = 'total_amt'
value_column = 'total_amt'

def build_hierarchical_dataframe(valid_trans, levels, value_column, color_column = None):
    """
    Build a hierarchy of levels for Sunburst or Treemap charts.

    Levels are given starting from the bottom to the top of the hierarchy,
    ie the last level corresponds to the root.
    """
    df_all_trees = pd.DataFrame(columns=['id', 'parent', 'value'])
    for i, level in enumerate(levels):
        df_tree = pd.DataFrame(columns=['id', 'parent', 'value'])
        dfg = valid_trans.groupby(levels[i:]).sum()
        dfg = dfg.reset_index()
        df_tree['id'] = dfg[level].copy()
        if i < len(levels) - 1:
            df_tree['parent'] = dfg[levels[i+1]].copy()
        else:
            df_tree['parent'] = 'total'
        df_tree['value'] = dfg[value_column]
        df_all_trees = df_all_trees.append(df_tree, ignore_index=True)
    total = pd.Series(dict(id='total', parent='',
                              value=valid_trans[value_column].sum()))
    df_all_trees = df_all_trees.append(total, ignore_index=True)
    return df_all_trees

绘制旭日形的数据框: DataFrame

绘制 Plotly Go Sunburst 的代码:

fig.add_trace(go.Sunburst(
    labels=df_all_trees['id'],
    parents=df_all_trees['parent'],
    values=df_all_trees['value'],
    branchvalues='total',
    marker=dict(
        colorscale='RdBu'),
    hovertemplate='<b>%{label} </b><br> Percent: %{value:.2f}',
    maxdepth=2
    ))

fig.show()

Plotly Go 的结果:Missing Figure

此任务的子集数据框代码:

c_names = ['year','prod_cat','prod_subcat','total_amt']
var = {
    'year': [2011,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012,2012,2012,2012,2012,2012,2013,2013,2013,2013,2013,2013,2014,2014], 
    'prod_cat': ['Bags','Books','Books','Clothing','Clothing','Home and kitchen','Books','Books','Clothing','Clothing','Electronics','Electronics','Footwear','Footwear','Home and kitchen','Home and kitchen','Books','Books','Clothing','Electronics','Home and kitchen','Home and kitchen','Bags','Bags'], 
    'prod_subcat': ['Mens','Academic','Fiction','Mens','Women','Furnishing','Non-Fiction','Non-Fiction','Kids','Women','Audio and video','Computers','Mens','Women','Furnishing','Kitchen','Academic','Non-Fiction','Women','Mobiles','Bath','Furnishing','Mens','Women'], 
   'total_amt': [3443.18,5922.8,1049.75,1602.25,6497.4,3287.375,6342.7,2243.15,4760.34,2124.915,5878.6,1264.12,433.16,287.3,1221.025,3867.5,2897.31,2400.06,285.09,5707.325,5585.775,2103.92,3391.245,281.775]
}

valid_trans = pd.DataFrame(data = var, columns = c_names)

【问题讨论】:

    标签: python pandas plot plotly sunburst-diagram


    【解决方案1】:

    要实现 2dp 百分比,这是一个更新跟踪的简单案例。您可以使用 plotly express 或 graph 对象。如果使用图形对象,使用 plotly express 来构造 go 的输入会使编码更简单 情节表达做结构化

    pxfig = px.sunburst(valid_trans, path=['year','prod_cat']#,'prod_subcat']
                        , values='total_amt')
    
    

    2dp 百分比...

    pxfig.update_layout(margin=dict(t=0, l=0, r=0, b=0)).update_traces(texttemplate="%{label}<br>%{percentEntry:.2%}")
    

    图形对象

    • 使用 plotly express 中的结构
    ig =go.Figure(go.Sunburst(
     ids=pxfig.data[0]["ids"],
      labels= pxfig.data[0]["labels"],
      parents= pxfig.data[0]["parents"],
        values=pxfig.data[0]["values"],
        branchvalues="total",
        texttemplate="%{label}<br>%{percentEntry:.2%}"
    ))
    fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))
    
    
    

    【讨论】:

    • 谢谢你,你真的救了我的命,我还有一个问题要问,如何根据总量使它成为连续颜色?例如,销售额越高,颜色越深。
    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多