简体   繁体   中英

Plotly express: Grouped and stacked of specific data colomns

I have a table of 6 colomns, as follows:

在此处输入图像描述

I need to prepare a graph of stacked and grouped like the following (I didn't show here the E, but it is in the colomn of C & D): 在此处输入图像描述

I've tried using this line:

px.bar(df2, x="Year", y=["Year", "A", "B", "C", "D", "E"], barmode="group").show()

But obviosuly it does not work as expected (since I don't know how to 'tell' which colomns I want to stack together). I get this graph: 在此处输入图像描述

Can anyone help me define the colomns I want to stack? (ie, A & B, C & D & E) I want to do it in plotly.express.

The expected output is a grouping of stacked graphs, but as far as I know, there is no easy way to achieve this. So I created the data structure based on an example of creating a graph from multiple indices. The reference's can be found here . I manually created multiple indexes for the x-axis and specified the columns for each. The limitation with this graph is that the column names are required. The spacing of bars per group cannot be adjusted as in the expected output graph.

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(x=[[2019,2020,2021],['AB','AB','AB']], y=df['A'], name='A'))
fig.add_trace(go.Bar(x=[[2019,2020,2021],['AB','AB','AB']], y=df['B'], name='B'))
fig.add_trace(go.Bar(x=[[2019,2020,2021],['CD','CD','CD']], y=df['C'], name='C'))
fig.add_trace(go.Bar(x=[[2019,2020,2021],['CD','CD','CD']], y=df['D'], name='D'))

fig.update_traces(selector=dict(type='bar'), width=[0.85,0.85,0.85,0.85,0.85,0.85]) 
fig.update_layout(autosize=False, barmode='stack', bargap=0.0, bargroupgap=0.0, legend=dict(traceorder='normal'))

fig.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM