如何用两个类别绘制条形图?

时间:2021-06-16 15:02:09

标签: python plot plotly bar-chart plotly-dash

我有这样的数据

import pandas as pd
df = pd.DataFrame(
dict(
    week=[1, 1, 2, 2, 3, 3] * 2,
    layout=["classic", "classic", "modern", "modern"] * 3,
    response=["conversion", "exit"] * 6,
    cnt=[26, 23, 45, 34, 55, 44, 53, 27, 28, 25, 30, 34],))

而且我需要像excel一样使用plotly获得这样的条形图: enter image description here

我不能使用两个类别的主要问题。我的代码:

px.bar(
    data_frame=df,
    x='week',
    y='cnt',
    template='plotly_dark',
    color = 'layout'
)

和结果: enter image description here

但我无法像excel示例中那样显示有关“响应”的信息

1 个答案:

答案 0 :(得分:5)

在我看来,最灵活的方法是使用 go.Figure() 然后

fig.add_traces(go.Bar(x=dfp['week'], y = dfp['cnt'], name = v))

对于 v 中的每个值 ['conversion - classic', 'conversion - modern', 'exit - classic', 'exit - modern'],如下所示:

fig = go.Figure()
for v in df['value'].unique():
    dfp = df[df['value']==v]
    fig.add_traces(go.Bar(x=dfp['week'], y = dfp['cnt'], name = v))
fig.update_layout(barmode='stack', template='plotly_dark')
fig.show()

情节:

enter image description here

据我所知,这应该与您的 Excel 输出非常相似。

完整代码:

import pandas as pd
import plotly.graph_objects as go
import plotly.express as px

df = pd.DataFrame(
dict(
    week=[1, 1, 2, 2, 3, 3] * 2,
    layout=["classic", "classic", "modern", "modern"] * 3,
    response=["conversion", "exit"] * 6,
    cnt=[26, 23, 45, 34, 55, 44, 53, 27, 28, 25, 30, 34],))

df['value'] = df['response'] + ' - ' + df['layout']
df = df.sort_values('value')
# df2 = df.groupby(['value', 'week']).sum().reset_index().sort_values('value')

fig = go.Figure()
for v in df['value'].unique():
    dfp = df[df['value']==v]
    fig.add_traces(go.Bar(x=dfp['week'], y = dfp['cnt'], name = v))
fig.update_layout(barmode='stack', template='plotly_dark')
fig.show()