我可以在 plotly 中叠加两个堆叠条形图吗?

Can I overlay two stacked bar charts in plotly?

使用 pandas 和 matplotlib,我为我们的团队创建了一个方便的图形来监控收入。对于我们的每个客户,它显示上个月(浅灰色)、最佳月份(深灰色)和本月的预测范围(绿色)。

它基本上是两个不同宽度的堆叠条形图。

ax = df.plot(kind='barh', x='company', y=['last_month', 'best-last'], width=0.2, color=context_colors, lw=0, stacked=True)

df.plot(kind='barh', x='company', y=['forecast_low', 'hi-lo'], stacked=True, colors=range_colors, lw=0, ax=ax)

在 python 中表现出色。出于不值得深入探讨的原因,该图像无法在其需要继续访问的网站上显示正确的大小。所以我第一次尝试 plotly 。

我没能找到类似的功能。我尝试构建单独的堆叠图表,然后通过 运行 顺序 iplot 组合它们,但它只是构建了两个单独的图。 例如

iplot(fig)
iplot(fig2)

尝试合并无花果是不好的(例如iplot(fig, fig2)),它只会绘制第一个中的数据。

对于如何在 plotly 中复制有什么建议吗?

图表可能需要一些调整,但它绝对可以用 Plotly 实现。

  • 向两条轨迹添加 orientation='h' 使它们成为 h水平
  • barmode='stack' 添加到您的 layout 以堆叠条形图
  • 确保xy匹配右轴
  • 堆叠轨迹的 x 值应该只是两条轨迹之间的差异,即 x=df['best'] - df['last month']
  • 对于预测点,您可以使用 mode 设置为 markers 的散点图或添加 shapes(下图都有)。

import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd

df = pd.DataFrame(
    {'last month': [10, 15, 12],
     'best': [13, 20, 16],
     'forecast': [11, 17, 14],
     'animal': ['giraffe', 'orangutan', 'monkey']
     }
)

trace1 = go.Bar(
    y=df['animal'],
    x=df['last month'],
    name='last month',
    orientation='h'
)
trace2 = go.Bar(
    y=df['animal'],
    x=df['best'] - df['last month'],
    name='best month',
    orientation='h',
)
trace3 = go.Scatter(
    y=df['animal'],
    x=df['forecast'],
    name='forecasst',
    mode='markers',
    marker= {'size': 20, 'symbol': 'square'}
)
data = [trace1, trace2, trace3]

shapes = list()
for i, x in enumerate(df['animal']):
    shapes.append({
        'type': 'rect',
        'x0': df.forecast[i] - 1,
        'x1': df.forecast[i] + 1,
        'y0': i - 0.5,
        'y1': i + 0.5,
        'line': {
            'color': 'rgba(0, 128, 0, 1)',
            'width': 2,
            },
        'fillcolor': 'rgba(0, 128, 0, 0.5)'
        }
    )
layout = go.Layout(
    barmode='stack',
    shapes=shapes
)

fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig)