如何从数据帧中以绘图方式绘制堆叠的条形图?

时间:2020-10-02 20:32:49

标签: python python-3.x pandas plotly plotly-python

我有一个df

name | week |      %
mike   Week 1     .45
mike   Week 2      0
mike   Week 3     .40
mike   Week 4     .15
cindy  Week 1     .25
cindy  Week 2     .25
cindy  Week 3     .25
cindy  Week 4     .25

采样的df,其中我的实际df有更多名称

我正试图每周绘制每个名字的所有值,

我的密谋代码如下:

    import plotly.graph_objects as go
    names= df['name'].unique()
    
    fig = go.Figure(data=[
        go.Bar(name='Week 1', x=names, y=[.15, .29, .19, .07]),
        go.Bar(name='Week 2', x=names, y=[.24, .15, .15, .15]),
        go.Bar(name='Week 3', x=names, y=[.20, .19, .17, .11]),
        go.Bar(name='Week 4', x=names, y=[.41, .37, .49, .67]),
    
    
    ])
    # Change the bar mode
    fig.update_layout(barmode='stack', title = 'title',xaxis_title='Month',
                      yaxis=dict(
            tickformat="%",
        ))

fig.show()

但是我不想手动在y中键入第1周,第2周,第3周等的每个值。如何创建参考,其中绘图代码中每个星期的y都将引用第1周中的所有值,因此我不必键入?谢谢

1 个答案:

答案 0 :(得分:1)

import plotly.express as px
import pandas as pd

# sample dataframe
data = {'name': ['mike', 'mike', 'mike', 'mike', 'cindy', 'cindy', 'cindy', 'cindy'],
        'week': ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 1', 'Week 2', 'Week 3', 'Week 4'],
        '%': [0.45, 0.0, 0.4, 0.15, 0.25, 0.25, 0.25, 0.25]}
df = pd.DataFrame(data)

# display(df)
    name    week     %
0   mike  Week 1  0.45
1   mike  Week 2  0.00
2   mike  Week 3  0.40
3   mike  Week 4  0.15
4  cindy  Week 1  0.25
5  cindy  Week 2  0.25
6  cindy  Week 3  0.25
7  cindy  Week 4  0.25

# plot the long (tidy) dataframe
fig = px.bar(df, x="name", y="%", color="week", title="Title", barmode='stack')
fig.update_layout(xaxis_title='Name', yaxis=dict(tickformat="%",))
fig.show()
  • plotly.graph_objects需要使用plotly.graph_obj来构建堆叠条形图的每个级别
  • 使用列表理解,可以将df.groupby对象解压缩为必要的形式,例如go.Figure
import plotly.graph_objects as go

# using df from above, use groupby and a list comprehension to create data
data = [go.Bar(name=group, x=dfg['name'], y=dfg['%']) for group, dfg in df.groupby(by='week')]

# plot the figure
x = go.Figure(data)
x.update_layout(barmode='stack', title='Title', xaxis_title='Name', yaxis=dict(tickformat="%",))
x.show()
  • 两个实现都产生以下图

enter image description here