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
plotly.express
, which takes a tidy (long) dataframe, by column name.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 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.