Mateusz Konopelski
Mateusz Konopelski

Reputation: 1042

plotly: descending order in grouped bar chart

I'm trying to

  1. create a nice plot which is sorted by LABEL and then by Value inside each LABEL.
  2. If possible remove labels on the bottom of the chart because I have explanation in legend.

libraries:

from plotly import graph_objs as go
import plotly.express as px
import pandas as pd

My data looks like this:

df = pd.DataFrame({'LABEL': ['1', '1', '2', '2', '3', '3', '3', '3'],
                 'Cat2': ['a',  'b',  'a', 'b', 'c', 'a', 'e', 'f'],
                 'Value': [3, 2, 1, 4, 1, 3, 4, 1]})
df.sort_values(by=['LABEL', 'Value'], ascending=[True, False],inplace=True)

enter image description here

Here is my try:

COLOR_MAP = {str(i): c for i, c in enumerate(px.colors.qualitative.Light24)}

fig = go.Figure()

for i in df['LABEL'].unique():
    df_ = df[df['LABEL'] == i]
    fig.add_trace(go.Bar(
        x=[df_['LABEL'], df_['Cat2']],
        y=df_['Value'],
        marker=dict(color=COLOR_MAP[i]),
        name=f'{i}'))

fig.update_layout(legend_title='Cat1')

fig.update_layout(
    xaxis=dict(tickangle=45))

fig.update_layout(xaxis={'categoryorder': 'trace'}) # I tried: 'total descending', 'category descending', 'array'

Result: enter image description here

My expectation: enter image description here

Thanks in advance!!

Upvotes: 4

Views: 1911

Answers (2)

tb.
tb.

Reputation: 789

I found the 'total descending' solution mentioned to do the opposite of what I expected. I used a similar 'total ascending' to solve a very similar problem in a much less complicated fashion using plotly express by adding the following before the fig.show() command:

fig.update_layout(xaxis={'categoryorder': 'total ascending'})

Upvotes: 0

Rob Raymond
Rob Raymond

Reputation: 31146

  • it's much simpler in plotly express
  • define a new column in dataframe that defines x
from plotly import graph_objs as go
import plotly.express as px
import pandas as pd

df = pd.DataFrame(
    {
        "LABEL": ["1", "1", "2", "2", "3", "3", "3", "3"],
        "Cat2": ["a", "b", "a", "b", "c", "a", "e", "f"],
        "Value": [3, 2, 1, 4, 1, 3, 4, 1],
    }
)
df.sort_values(by=["LABEL", "Value"], ascending=[True, False], inplace=True)

# define a concatenated column for x
df = df.assign(labx=df["LABEL"] + df["Cat2"])
px.bar(
    df,
    x="labx",
    y="Value",
    hover_data=["Cat2"],
    color="LABEL",
    color_discrete_sequence=px.colors.qualitative.Light24,
).update_layout(
    xaxis={"tickmode": "array", "tickvals": df["labx"], "ticktext": df["Cat2"]}
)

enter image description here

without plotly express

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(
    go.Bar(
        x=df["labx"],
        y=df["Value"],
        marker_color=df["LABEL"]
        .map(
            {v: c for v, c in zip(df["LABEL"].unique(), px.colors.qualitative.Light24)}
        )
        .values,
    )
).update_layout(
    xaxis={"tickmode": "array", "tickvals": df["labx"], "ticktext": df["Cat2"]}
)

Upvotes: 2

Related Questions