基本上,我从 python 中的 plotly 教程中获得了以下代码:
import plotly.graph_objects as go
animals=['giraffes', 'orangutans', 'monkeys']
fig = go.Figure(data=[
go.Bar(name='SF Zoo', x=animals, y=[20, 14, 23]),
go.Bar(name='LA Zoo', x=animals, y=[12, 18, 29])
])
# Change the bar mode
fig.update_layout(barmode='group')
fig.show()
此代码生成一个简单的条形图,按类型(动物)和颜色(“SF Zoo”、“LA Zoo”)分隔。我想在红色条上方添加一个百分比来表示红色条值与相应的蓝色/紫色条值之间的百分比差异,如下图所示:
这个应该怎么写相应的代码?
编辑:我只想为红色条添加百分比,而不是在红色条上,而是在它们上方,如图所示
最佳答案
为了实现这一点,您应该拥有 y 值的列表以及百分比将超出 go.bar
的列表,如下所示:
y1 = [20, 14, 23]
y2 = [12, 18, 29]
c = []
为了计算百分比(向下舍入,您可以通过将 math.floor()
替换为 math.ceil()
来更改为向上舍入),您可以使用这个:
i = 0
while i < len(y1):
i = i
if y1[i] > y2[i]:
q = y1[i]-y2[i]
c.append( '-' + str(math.floor(q/y1[i]*100)) + '%')
i=i+1
if y1[i] < y2[i]:
t = y2[i]-y1[i]
c.append('+' + str(math.floor(t/y1[i]*100)) + '%')
i=i+1
这只是找到 y 值之间的差异,然后除以您试图从中找到百分比的原始值,将其乘以 100,使其成为百分比。
从那里您应该将您的y-values
设置为等于您之前设置的列表,同时将文本设置为等于百分比列表,c
。您必须做的另一件事是将 textposition
设置为外部,因为默认值为 none
。
fig = go.Figure(data=[
go.Bar(name='SF Zoo', x=animals, y=y1),
go.Bar(name='LA Zoo', x=animals, y=y2, text=c, textposition='outside')
])
# Change the bar mode
fig.update_layout(barmode='group')
fig.show()
完整代码如下:
import plotly.graph_objects as go
import math
y1 = [20, 14, 23]
y2 = [12, 18, 29]
animals=['giraffes', 'orangutans', 'monkeys']
c = []
i = 0
while i < len(y1):
i = i
if y1[i] > y2[i]:
q = y1[i]-y2[i]
c.append( '-' + str(math.floor(q/y1[i]*100)) + '%')
i=i+1
if y1[i] < y2[i]:
t = y2[i]-y1[i]
c.append('+' + str(math.floor(t/y1[i]*100)) + '%')
i=i+1
print(c)
fig = go.Figure(data=[
go.Bar(name='SF Zoo', x=animals, y=y1),
go.Bar(name='LA Zoo', x=animals, y=y2, text=c, textposition='outside')
])
# Change the bar mode
fig.update_layout(barmode='group')
fig.show()
输出的图是这样的:
关于python - 如何在 plotly 中添加条形图上方的百分比差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67221226/