简体   繁体   中英

Stacked bar plot in python / plotly (express): grouping / ordering of bars

I have data in a dataframe that I want to plot with a stacked bar plot:

test_df = pd.DataFrame([[1, 5, 1, 'A'], [2, 10, 1, 'B'], [3, 3, 1, 'A']], columns = ('ID', 'Value', 'Bucket', 'Type'))

if I do the plot with Plotly Express I get bars stacked on each other and correctly ordered (based on the index):

fig = px.bar(test_df, x='Bucket', y='Value', barmode='stack')

However, I want to color the data based on Type, hence I go for

fig = px.bar(test_df, x='Bucket', y='Value', barmode='stack', color='Type')

在此处输入图像描述

This works, except now the ordering is messed up, because all bars are now grouped by Type. I looked through the docs of Plotly Express and couldn't find a way to specify the ordering of the bars independently. Any tips on how to do this?

I found this one here, but the scenario is a bit different and the options mentioned there don't seem to help me: How to disable plotly express from grouping bars based on color?

Edit: This goes into the right direction, but not with using Plotly Express, but rather Plotly graph_objects:

import plotly.graph_objects as go
test_df = pd.DataFrame([[1, 5, 1, 'A', 'red'], [2, 10, 1, 'B', 'blue'], [3, 3, 1, 'A', 'red']], columns = ('ID', 'Value', 'Bucket', 'Type', 'Color'))
fig = go.Figure()
fig.add_trace(go.Bar(x=test_df["Bucket"], y=test_df["Value"], marker_color=test_df["Color"]))

Output: 在此处输入图像描述

Still, I'd prefer the Express version, because so many things are easier to handle there (Legend, Hover properties etc.).

The only way I can understand your question is that you don't want B to be stacked on top of A , but rather the opposite. If that's the case, then you can get what you want through:

fig.data = fig.data[::-1]
fig.layout.legend.traceorder = 'reversed'

在此处输入图像描述

Some details:

fig.data = fig.data[::-1] simply reverses the order that the traces appear in fig.data and ultimately in the plotted figure itself. This will however reverse the order of the legend as well. So without fig.layout.legend.traceorder = 'reversed' the result would be:

在此处输入图像描述

And so it follows that the complete work-around looks like this:

fig.data = fig.data[::-1]
fig.layout.legend.traceorder = 'reversed'

Complete code:

import pandas as px
import plotly.express as px
test_df = pd.DataFrame([[1, 5, 1, 'A'], [2, 10, 1, 'B'], [3, 3, 1, 'A']], columns = ('ID', 'Value', 'Bucket', 'Type'))
fig = px.bar(test_df, x='Bucket', y='Value', barmode='stack', color='Type')
fig.data = fig.data[::-1]
fig.layout.legend.traceorder = 'reversed'
fig.show()

Ok, sorry for the long delay on this, but I finally got around to solving this.
My solution is possibly not the most straight forward one, but it does work.

The basic idea is to use graph_objects instead of express and then iterate over the dataframe and add each bar as a separate trace. This way, each trace can get a name that can be grouped in a certain way (which is not possible if adding all bars in a single trace, or at least I could not find a way). Unfortunately, the ordering of the legend is messed up (if you have more then 2 buckets) and there is no way in plotly currently to sort it. But that's a minor thing.

The main thing that bothers me is that this could've been so much easier if plotly.express allowed for manual ordering of the bars by a certain column. Maybe I'll submit that as a suggestion.

import pandas as pd
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default = "browser"

test_df = pd.DataFrame(
    [[1, 5, 1, 'B'], [3, 3, 1, 'A'], [5, 10, 1, 'B'],
     [2, 8, 2, 'B'], [4, 5, 2, 'A'], [6, 3, 2, 'A']],
    columns = ('ID', 'Value', 'Bucket', 'Type'))
# add named colors to the dataframe based on type
test_df.loc[test_df['Type'] == 'A', 'Color'] = 'Crimson'
test_df.loc[test_df['Type'] == 'B', 'Color'] = 'ForestGreen'
# ensure that the dataframe is sorted by the values
test_df.sort_values('ID', inplace=True)

fig = go.Figure()
# it's tedious to iterate over each item, but only this way we can ensure that everything is correctly ordered and labelled
# Set up legend_show_dict to check if an item should be shown or not. This should be only done for the first occurrence to avoid duplication.
legend_show_dict = {}
for i, row in test_df.iterrows():
    if row['Type'] in legend_show_dict:
        legend_show = legend_show_dict[row['Type']]
    else:
        legend_show = True
        legend_show_dict[row['Type']] = False
    fig.add_trace(
        go.Bar(
            x=[row['Bucket']],
            y=[row['Value']],
            marker_color=row['Color'],
            name=row['Type'],
            legendgroup=row['Type'],
            showlegend=legend_show,
            hovertemplate="<br>".join([
            'ID: ' + str(row['ID']),
            'Value: ' + str(row['Value']),
            'Bucket: ' + str(row['Value']),
            'Type: ' + row['Type'],
            ])
           ))
fig.update_layout(
    xaxis={'categoryorder': 'category ascending', 'title': 'Bucket'},
    yaxis={'title': 'Value'},
    legend={'traceorder': 'normal'}
    )
fig.update_layout(barmode='stack', font_size=20)
fig.show()

This is what it should look like then:
输出

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