# Plotly Express Bar Charts: Grouped, Stacked, and Labeled

> Plotly Express bar chart guide: px.bar with barmode="group", stacked and percent bars, text_auto labels, sorted horizontal bars, aggregating rows, and coloring by value.

Source: https://www.pythoncharts.com/plotly/plotly-express-bar-charts/ | Published: 2026-11-26 | Author: Alex Scott | Category: Plotly | Tags: plotly, plotly express, px, bar-chart, grouped-bar-chart, stacked-bar-chart

Make a bar chart in Plotly with `px.bar(df, x="category", y="value")`. Add `color="column"` to split the bars into series, which stack by default, or pass `barmode="group"` to put them side by side. `text_auto=True` writes the values on the bars.

## Quick Example

```python
import numpy as np
import pandas as pd
import plotly.express as px

rng = np.random.default_rng(63)
genres = ["Fiction", "Mystery", "Science", "History", "Poetry"]
base = {"Fiction": 420, "Mystery": 310, "Science": 240, "History": 190, "Poetry": 70}
orders = pd.DataFrame(
    [(genre, fmt, int(base[genre] * share * rng.uniform(0.85, 1.15)))
     for genre in genres
     for fmt, share in [("Print", 0.55), ("Ebook", 0.30), ("Audio", 0.15)]],
    columns=["genre", "format", "units"],
)

fig = px.bar(orders, x="genre", y="units", color="format", barmode="group",
             text_auto=True, title="Books sold by genre and format",
             color_discrete_sequence=["#1d4ed8", "#f59e0b", "#10b981"],
             labels={"genre": "Genre", "units": "Units sold", "format": "Format"})
fig.update_traces(textposition="outside", cliponaxis=False)
fig.show()
```

![Grouped Plotly Express bar chart of units sold for five book genres split into print, ebook, and audio formats, with values above the bars](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/images/plotly-express-bar-grouped.png)

Fiction sells the most in every format, with 235 print copies against 144 ebooks and 57 audiobooks. Hover a bar to see its values, and click a legend entry to hide that format. The code targets Plotly 6.x.

## The px.bar Arguments That Matter

| Argument | What it does |
|---|---|
| `x`, `y` | Column names for categories and values |
| `color` | Column that splits bars into series (or sets a color scale if numeric) |
| `barmode` | `"relative"` (stacked, the default), `"group"`, or `"overlay"` |
| `text_auto` | `True`, or a format string like `".1f"` or `".2s"` |
| `text` | Column to use as the bar label |
| `orientation` | `"h"` for horizontal bars |
| `category_orders` | Fixed category order, e.g. `{"genre": [...]}` |
| `labels` | Display names for columns in axis titles, legend, and hover |
| `facet_col`, `facet_row` | Split into small multiples |
| `color_discrete_sequence`, `color_discrete_map` | Series colors |

`px.bar` expects long-form data: one row per bar, with a column that names the series. If your data has one column per series, either reshape it with `df.melt()` or pass a list, as in `y=["print", "ebook", "audio"]`.

## Stacked Bar Chart

Leave out `barmode` and the series stack.

```python
fig = px.bar(orders, x="genre", y="units", color="format",
             title="Stacked bars (the default)",
             color_discrete_sequence=["#1d4ed8", "#f59e0b", "#10b981"])
fig.show()
```

![Stacked Plotly Express bar chart of book sales by genre with print, ebook, and audio segments](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/images/plotly-express-bar-stacked.png)

The default mode is `"relative"`: positive values stack upward from zero and negative values stack downward.

## 100% Stacked Bar Chart

To compare the mix within each category regardless of its total, compute each row's share of its group and plot that column.

```python
orders["share"] = 100 * orders["units"] / orders.groupby("genre")["units"].transform("sum")
fig = px.bar(orders, x="genre", y="share", color="format", text_auto=".0f",
             title="Share of each genre's sales by format (%)",
             color_discrete_sequence=["#1d4ed8", "#f59e0b", "#10b981"],
             labels={"share": "Percent of units"})
fig.show()
```

![Percent stacked bar chart with percentage labels showing print at roughly 54 to 59 percent of sales in every book genre](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/images/plotly-express-bar-percent.png)

Print makes up between 54% and 59% of sales in every genre. `fig.update_layout(barnorm="percent")` rescales the bar heights without the extra column, but `text_auto` labels then still show the raw counts. The [stacked bar charts in Python](https://www.pythoncharts.com/python/stacked-bar-charts/) post covers the Matplotlib and pandas versions.

## Sorted Horizontal Bar Chart with Labels

Horizontal bars suit long category names. Plotly draws the first row at the bottom, so sort **ascending** to get the largest value on top. `texttemplate` formats the label, here with a dollar sign and a thousands separator.

```python
rents = pd.DataFrame({
    "area": ["Harborview", "Old Mill", "Eastgate", "Parkside", "Brickyard", "Hillcrest", "Midtown", "Fernwood"],
    "rent": [1650, 980, 870, 1020, 760, 640, 1180, 470],
})
fig = px.bar(rents.sort_values("rent"), x="rent", y="area", orientation="h",
             text="rent", title="Median one-bedroom rent by neighborhood ($)",
             color_discrete_sequence=["#7c3aed"])
fig.update_traces(texttemplate="$%{x:,}", textposition="outside", cliponaxis=False)
fig.update_xaxes(range=[0, 1900], title=None)
fig.update_yaxes(title=None)
fig.show()
```

![Horizontal bar chart of sample rents in eight neighborhoods sorted from Harborview at 1,650 dollars down to Fernwood at 470 dollars, each bar labeled](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/images/plotly-express-bar-horizontal.png)

`textposition="outside"` puts labels past the end of each bar. `cliponaxis=False` and a little extra axis range keep the longest one from being cut off.

## Aggregate Your Data First

`px.bar` draws one rectangle per row. Give it raw records and the rows in each category pile up, so the bar height is their sum, with faint lines between the pieces. For an average, aggregate with pandas and plot the result.

```python
tickets = pd.DataFrame({
    "team": rng.choice(["Billing", "Onboarding", "API", "Mobile"], 240, p=[.35, .3, .2, .15]),
    "hours": rng.gamma(2.0, 3.0, 240).round(1),
})
summary = (tickets.groupby("team", as_index=False)
           .agg(avg_hours=("hours", "mean"), tickets=("hours", "size")))
fig = px.bar(summary, x="team", y="avg_hours", text_auto=".1f",
             hover_data={"tickets": True, "avg_hours": ":.2f"},
             title="Average hours to resolve a ticket",
             color_discrete_sequence=["#0f766e"])
fig.update_xaxes(categoryorder="total descending")
fig.show()
```

![Bar chart of average ticket resolution hours by team, sorted from Mobile at 6.8 down to Billing at 5.5](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/images/plotly-express-bar-aggregated.png)

Mobile is slowest at 6.8 hours on average even though it handles the fewest tickets. `categoryorder="total descending"` sorts the bars without touching the DataFrame.

If you only need counts or a quick sum or mean, `px.histogram(tickets, x="team", y="hours", histfunc="avg")` aggregates for you.

## Color Bars by Value

Pass a numeric column to `color` to use a continuous scale. `color_continuous_midpoint=0` anchors the middle color at zero, so gains and losses read correctly.

```python
growth = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    "change": [4.2, 2.8, -1.5, -3.9, -0.8, 1.9, 5.1, 6.4, 2.2, -2.4, 3.3, 7.8],
})
fig = px.bar(growth, x="month", y="change", color="change",
             color_continuous_scale="RdYlGn", color_continuous_midpoint=0,
             title="Month-over-month revenue change (%)")
fig.update_layout(coloraxis_showscale=False)
fig.show()
```

![Monthly revenue change bar chart with positive months in green and negative months in orange and yellow, centered at zero](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/images/plotly-express-bar-color.png)

For exactly two colors, add a column such as `growth["sign"] = np.where(growth["change"] > 0, "up", "down")` and pass it to `color` with a `color_discrete_map`.

## px.bar vs go.Bar vs px.histogram

| Use | When |
|---|---|
| `px.bar` | Your data is a DataFrame with one row per bar |
| `px.histogram` | You want Plotly to count, sum, or average raw rows |
| `go.Bar` | You're building traces by hand, or mixing bars into [subplots](https://www.pythoncharts.com/plotly/plotly-make-subplots/) |

## Practical Tips

- Set the order of categories with `category_orders` when it has meaning (months, sizes, survey answers).
- `bargap` and `bargroupgap` in `update_layout` control the spacing between bar groups and within them.
- If labels on stacked segments are unreadably small, add `uniformtext_minsize=10, uniformtext_mode="hide"` to `update_layout`.
- Keep the value axis starting at zero. Bar length is what readers compare.
- To format the axis ticks themselves, see [formatting axes as percentages or currency](https://www.pythoncharts.com/plotly/plotly-format-axes-percentages-currency/).

## Similar Topics

- [How to Make Subplots in Plotly with make_subplots](https://www.pythoncharts.com/plotly/plotly-make-subplots/)
- [How to Rotate Tick Labels on Plotly Express Charts](https://www.pythoncharts.com/plotly/plotly-rotate-tick-labels-plotly-express/)
- [Customize Hover Tooltips in Plotly](https://www.pythoncharts.com/plotly/plotly-customize-hover-tooltips/)
