英文:
How to do stacked barplots and avoid error bars being hidden in Plotly
问题
我试图制作堆叠条形图,并在两个条形之间添加对称的误差线,然而,误差线被第二个 go.Bar 的实例遮挡。我在文档中找不到解决方法。有办法改变绘图元素的顺序以强制显示误差线吗?
英文:
I am trying to do stacked bars plots with symmetric error bars in between the two bars, however, the error bars become hidden by the second instance of go.Bar (Example below).
import plotly.graph_objects as go
x_values = ['A','B','C','D','E']
y1_values = [0.527, 0.519, 0.497, 0.458, 0.445]
y2_values = [0.473, 0.481, 0.503, 0.542, 0.555]
y_errors = [0.05, 0.065, 0.158, 0.07, 0.056]
fig = go.Figure(data=[
go.Bar(name='NAME1', x=x_values, y=y1_values, error_y=dict(type="data", array=y_errors)),
go.Bar(name='NAME2', x=x_values, y=y2_values)
])
# Change the bar mode
fig.update_layout(barmode='stack')
fig.show()
I could not find a solution to this in the documentation. Is there a way to alter the order of plot elements to force the error bar to appear?
答案1
得分: 2
你可以通过首先绘制 NAME2
条形,然后是 NAME1
条形来解决这个问题 - 你需要将 NAME2 条形的基准设置为 NAME1 条形的 y1_values
(以便NAME2条形从NAME1条形将要在的地方开始),然后将 NAME1 条形的基准设置为 0 以确保它们从 y=0 开始。
英文:
You can get around this by plotting the NAME2
bars first, followed by the NAME1
bars – you would need to set the base of the NAME2 bars to be the y1_values
of the NAME1 bars (so that the NAME2 bars start from where the NAME1 bars will be), then set the base of the NAME1 bars to be 0 to ensure they start from y=0.
import plotly.graph_objects as go
x_values = ['A','B','C','D','E']
y1_values = [0.527, 0.519, 0.497, 0.458, 0.445]
y2_values = [0.473, 0.481, 0.503, 0.542, 0.555]
y_errors = [0.05, 0.065, 0.158, 0.07, 0.056]
fig = go.Figure(data=[
go.Bar(name='NAME2', x=x_values, y=y2_values, base=y1_values),
go.Bar(name='NAME1', x=x_values, y=y1_values, error_y=dict(type="data", array=y_errors), base=[0]*5)
])
# Change the bar mode
fig.update_layout(barmode='stack')
fig.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论