3

I have a df as

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

sampled df where my actual df has many more names

I am trying to plot all of the values of each name per week,

my plotly code is below:

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

But I do not want to manually type out in y each of the values for week 1 then week 2 then week 3 and so on. How can I create a reference where y for each week in the plotting code will refer to all the values in week 1 so I dont have to type out? Thanks

0

1 Answer 1

5
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 requires a plotly.graph_obj, to construct each level of the stacked bar plot
  • Using a list-comprehension, a df.groupby object can be unpacked into the necessary form, for 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()
  • Both implementations produce the following plot

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.