【问题标题】:Shape positioning in categorical grouped bar chart分类分组条形图中的形状定位
【发布时间】:2020-12-22 15:18:13
【问题描述】:

如何将形状放在下面的分类条形图中,在条形中间指定SF Zoo 中的长颈鹿数量(如附图中的洋红色所示)?

import plotly.graph_objects as go
import plotly.express as px
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')

# Shape
fig.add_trace(go.Scatter(x=['giraffes', 'giraffes', 'orangutans', 'orangutans'],
                         y=[21, 25, 25, 16],
                         fill=None, mode="lines", line=dict(color='rgba(0,0,0,1)',width=2),
                         showlegend=False
                        )
             )

    
fig.show()

【问题讨论】:

  • 我认为如果没有某种骇人听闻/脆弱的解决方案,这是不可能的。

标签: plotly bar-chart positioning


【解决方案1】:

正如@Maximilian Peters 指出的那样,没有一种很好的方法可以在分类坐标之间任意引用一个点。

你能做的最好的是将xref设置为paper,这意味着x轴被缩放到0到1之间。然后你必须猜测并检查x坐标应该在哪里排列你想要他们的地方。由于您的 y 轴是数字的,因此您可以直接引用您喜欢的 y 值。经过反复试验,在 (0.10, 20), (0,10, 25), (0.44, 25), (0.44, 14) 之间画线可以让您非常接近所需的注释。

这绝对是 hacky,如果您添加更多条形或以任何方式更改条形的宽度,则无法推广。

import plotly.graph_objects as go
import plotly.express as px
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')

# Shape composed of three lines, looping through coordinates
x_coords = [0.10, 0.10, 0.44, 0.44]
y_coords = [20, 25, 25, 14]
for i in range(1,len(x_coords)):
    fig.add_shape(
        type="line",
        xref="paper",
        x0=x_coords[i-1], 
        y0=y_coords[i-1], 
        x1=x_coords[i], 
        y1=y_coords[i],
        line=dict(color="magenta",width=3)
    )
    
fig.show()

【讨论】:

  • 非常感谢@Derek O。我想我可以通过xref="paper", yref="paper" 使用绝对定位,从而分别绘制3 条线,但是,for 循环看起来更优雅(对此全新)。我希望 plotly 开发人员在未来为这个问题和统计注释提供更好的解决方案,特别是对分类数据。我需要做一个 2-way ANOVA 并将 p 值添加到类似的图表中,但我还没有在 Plotly 中找到一种方便的方法吗?
  • @hans 是的 Plotly 是一个很酷的库,交互式绘图很棒,但它们是以可调性为代价的。肯定有更多与分类条形图相关的功能需要添加,如果这个确切问题存在未解决的问题,我不会感到惊讶。如果您关于在条形图中添加 p 值的问题与此问题不同,请随时发布一个新问题,以便我或其他人可以帮助您解决这个问题!
猜你喜欢
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 2018-11-29
  • 1970-01-01
  • 2011-03-01
相关资源
最近更新 更多