如何将 2dp 添加到 Plotly Go Sunburst
How to add 2dp to Plotly Go Sunburst
此任务的 Objective:
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)
要实现 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%}")
graph_objects
- 使用来自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))
Objective:
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)
要实现 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%}")
graph_objects
- 使用来自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))