1

I have such data

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],))

And I need to get such barplot like in excel with plotly: enter image description here

The main problem that I can not use two categoies. My code:

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

and result: enter image description here

But i cannot display information about "response" like in excel example

1
  • How did my suggestion work out for you? Commented Jul 19, 2021 at 7:57

1 Answer 1

5

It seems to me that the most flexible way would be to use go.Figure() and then

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

for each value, v, in ['conversion - classic', 'conversion - modern', 'exit - classic', 'exit - modern'] like this:

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

Plot:

enter image description here

As far as I can tell, this should resemble your Excel output pretty closely.

Complete code:

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