python - Plotly:如何使用 go.Bar 向堆积条形图添加数据标签?
问题描述
我有一个堆叠的分组条形图,我想获取图表上每个条形的每个部分的数据标签。
我的图表如下:
stackData = {
"Leaders Now":[.52, .57, .38, .48],
"Bottom Now": [.20, .27, .19, .18],
# Use differece
"Leaders Plan": [.17, .06, .12, .16],
"Bottom Plan":[.15,.12,.09,.12],
"labels": [
"Revenue",
"Cost",
"Quality",
"Flexibility"
]
}
fig3 = go.Figure(
data=[
go.Bar(
name="Leaders Now",
x=stackData["labels"],
y=stackData["Leaders Now"],
offsetgroup=0,
marker_color = '#024a70'
),
go.Bar(
name="Leaders Plan",
x=stackData["labels"],
y=stackData["Leaders Plan"],
offsetgroup=0,
base=stackData["Leaders Now"],
marker_color = '#051c2c'
),
go.Bar(
name="Bottom Now",
x=stackData["labels"],
y=stackData["Bottom Now"],
offsetgroup=1,
marker_color = '#abe5f0'
),
go.Bar(
name="Bottom Plan",
x=stackData["labels"],
y=stackData["Bottom Plan"],
offsetgroup=1,
base=stackData["Bottom Now"],
marker_color = '#74d0f0'
)
],
layout=go.Layout(
title="Use Cases",
yaxis_title="% of Companies"
)
)
fig3.show()
我只想要条形图上每个项目的 % 值作为数据标签。这很容易通过 plotly express 但不确定为什么它不能使用诸如
fig3.update_traces(texttemplate='%{text:.0%}',textposition='auto')
谢谢!
解决方案
您只需text
为 each 指定属性go.Bar
,例如:
go.Bar(
name="Leaders Now",
x=stackData["labels"],
y=stackData["Leaders Now"],
offsetgroup=0,
marker_color = '#024a70',
text = stackData["Leaders Now"]
)
阴谋:
完整代码:
import plotly.graph_objects as go
import pandas as pd
stackData = {
"Leaders Now":[.52, .57, .38, .48],
"Bottom Now": [.20, .27, .19, .18],
# Use differece
"Leaders Plan": [.17, .06, .12, .16],
"Bottom Plan":[.15,.12,.09,.12],
"labels": [
"Revenue",
"Cost",
"Quality",
"Flexibility"
]
}
# stackData = pd.DataFrame(stackData)
fig3 = go.Figure(
data=[
go.Bar(
name="Leaders Now",
x=stackData["labels"],
y=stackData["Leaders Now"],
offsetgroup=0,
marker_color = '#024a70',
text = stackData["Leaders Now"]
),
go.Bar(
name="Leaders Plan",
x=stackData["labels"],
y=stackData["Leaders Plan"],
offsetgroup=0,
base=stackData["Leaders Now"],
marker_color = '#051c2c',
text= stackData["Leaders Plan"]
),
go.Bar(
name="Bottom Now",
x=stackData["labels"],
y=stackData["Bottom Now"],
offsetgroup=1,
marker_color = '#abe5f0',
text = stackData["Bottom Now"]
),
go.Bar(
name="Bottom Plan",
x=stackData["labels"],
y=stackData["Bottom Plan"],
offsetgroup=1,
base=stackData["Bottom Now"],
marker_color = '#74d0f0',
text = stackData["Bottom Plan"]
)
],
layout=go.Layout(
title="Use Cases",
yaxis_title="% of Companies"
)
)
f3 = fig3.full_figure_for_development(warn=False)
fig3.update_traces(texttemplate='%{text:.2%}', textposition='inside')
fig3.show()
推荐阅读
- blockchain - Ropsten 以太坊不显示交易信息
- java - Spring Boot - 仅允许经过身份验证的用户访问资源
- windows - 在 Windows 上构建 Docker 映像:入口点脚本“没有这样的文件或目录”
- vim - ncurses 库在 vim 构建期间不可用
- iot - thingsboard 小部件图表无法显示超过 6-7 小时的数据
- python - Python - C 编译错误 - gcc 失败
- haskell - 在 Haskell 中使用 `do..return` 表达式
- python - 如何在张量板中使用过滤器标签?
- c# - 在 Winform 中获取“真实”屏幕分辨率
- gimp - 在 gimp 中自动在文本层周围绘制边框的脚本