plotly - 分类分组条形图中的形状定位

标签 plotly bar-chart positioning

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

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()

picture of output

最佳答案

正如 @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()

enter image description here

关于plotly - 分类分组条形图中的形状定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65397557/

相关文章:

r - 将刻度线标签更改为 plotly 中的特定字符串

javascript - 更改 Plotly .js 中的标记形状

python - 如何阻止 Plotly Scatter 创建不存在的 X 值

javascript - NVD3 带条形图的对数 Y 轴

python - 无法在 matplotlib 中绘制条形图

html - 未指定的内容高度,自动溢出和页眉/页脚始终在 View 中,页面上没有滚轮

python - 在 Plotly 图中重新排序 Axis

javascript - Chart.js 中带标签的分组条形图

css - 为什么这个 CSS 不适合?

javascript - 在屏幕上安装绝对 div 弹出窗口