Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

Bar Plot in Matplotlib: Syntax, Grouped Bars, Error Bars

Bar plot in Python with Matplotlib: ax.bar syntax, grouped bars, error bars and bar labels for research figures, from the official docs.

Written and maintained by CASRAI Editorial Board

Last updated

This page is for researchers and graduate students who need a bar plot (also called a bar chart or bar graph) in Python for a paper, thesis or lab report. After reading it you can draw a basic and a grouped bar plot with Matplotlib, add error bars and value labels, and read what the call returns. All syntax below is from the official Matplotlib documentation (read 2026-11-07).

Short answer: call ax.bar(x, height) on a Matplotlib Axes. x can be a list of category names and height the value for each bar. The same call answers searches for “bar chart python”, “bar graph python”, “bar plot python” and “bar chart matplotlib”: in Python, Matplotlib’s bar is the base function that other libraries build on.

What it is used for in research

A bar plot compares a single value across discrete categories, such as a mean per treatment group, a count per species or a score per method. Because bar length encodes the value, a bar plot should start from zero; the bottom parameter of bar defaults to 0. For distributions of a continuous variable use a histogram instead (see histogram in Matplotlib).

Install or access (official source only)

The Matplotlib getting-started page lists these install routes:

pip install matplotlib
conda install -c conda-forge matplotlib

The same page also lists pixi add and uv add. For pip-specific problems see pip install matplotlib. The standard import convention from the official docs is shown in import matplotlib.pyplot as plt.

Step-by-step: draw a bar plot with Matplotlib

1. Basic bar plot from category names

The documented signature is Axes.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs). A list of strings is accepted for x.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(['A', 'B', 'C'], [1, 2, 3])
ax.set_ylabel('Value')
plt.show()

The pyplot shortcut plt.bar(['A','B','C'], [1,2,3]) does the same on the current Axes. The documentation also shows numeric positions with labels supplied separately: plt.bar(range(3), [1, 2, 3], tick_label=['A', 'B', 'C']).

2. Add error bars

yerr accepts a scalar, an array of shape (N,) for symmetric errors, or an array of shape (2, N) for separate lower and upper errors.

ax.bar(['A', 'B', 'C'], [1, 2, 3], yerr=[0.2, 0.3, 0.25])

Matplotlib draws whatever numbers you pass; it does not know whether they are standard deviations, standard errors or confidence intervals. State which one in the figure caption.

3. Style the bars

Keyword arguments are applied as Rectangle properties. The docs list color (alias for facecolor), edgecolor, alpha, linewidth, hatch and zorder, and label for legends (see legend in Matplotlib).

4. Grouped bars

Matplotlib’s gallery example for grouped bar charts uses the newer Axes.grouped_bar method, which the documentation says was added in Matplotlib 3.11 and whose API is still provisional. Signature: Axes.grouped_bar(heights, *, positions=None, group_spacing=1.5, bar_spacing=0, tick_labels=None, labels=None, orientation='vertical', colors=None, **kwargs). heights can be a dict (keys become legend labels), a list of arrays, a 2D array or a pandas DataFrame.

fig, ax = plt.subplots(layout='constrained')
res = ax.grouped_bar(
    {'Bill Depth': (18.35, 18.43, 14.98),
     'Bill Length': (38.79, 48.83, 47.50)},
    tick_labels=['Adelie', 'Chinstrap', 'Gentoo'],
    group_spacing=1)
for container in res.bar_containers:
    ax.bar_label(container, padding=3)
ax.set_ylabel('Length (mm)')
ax.legend(loc='upper left', ncols=2)
plt.show()

The values are the palmerpenguins means used in the official example. If your Matplotlib is older than 3.11, grouped_bar is not available; offset several ax.bar calls instead, using NumPy positions and a narrower width:

import numpy as np
x = np.arange(3)
w = 0.4
ax.bar(x - w/2, [18.35, 18.43, 14.98], w, label='Bill Depth')
ax.bar(x + w/2, [38.79, 48.83, 47.50], w, label='Bill Length')
ax.set_xticks(x, ['Adelie', 'Chinstrap', 'Gentoo'])
ax.legend()

5. Save the figure

Use fig.savefig('figure.png') (or a .pdf/.svg name for vector output) instead of plt.show() when the figure goes into a manuscript. Check the target journal’s figure instructions for required format and resolution.

Output and how to read it

bar returns a matplotlib.container.BarContainer: a collection of the Rectangle objects, one per bar. Pass it to ax.bar_label to print values above bars, as in the grouped example. grouped_bar returns an object whose guaranteed interface is bar_containers (one BarContainer per dataset) and remove().

Reading the figure: bar length is the value from a zero baseline; whiskers show the error quantity you passed in yerr; with align='center' (the default) each bar is centred on its x position, while 'edge' aligns the left edge (a negative width with 'edge' aligns the right edge).

Troubleshooting

  • AttributeError on grouped_bar: your Matplotlib predates 3.11. Upgrade with the install commands above or use the offset method.
  • Bars overlap in a grouped plot: with offset grouping, width times the number of series must not exceed the spacing between x positions (1 for np.arange).
  • Category labels collide: use layout='constrained' in plt.subplots as in the official example, or switch to horizontal bars.
  • Error bars look wrong: check that yerr has shape (N,) or (2, N) with N equal to the number of bars.
  • Nothing displays in a script: call plt.show() as in the getting-started convention.

Free alternatives

Tool When to consider it
seaborn barplot Computes group means and confidence intervals from a data frame for you; see seaborn barplot.
R ggplot2 geom_bar The equivalent in R; see bar plot in R.

FAQ

How do I make a bar chart in Python?

Import matplotlib.pyplot as plt, create an Axes with fig, ax = plt.subplots(), call ax.bar(categories, values) and finish with plt.show() or fig.savefig(...).

Is a bar graph, bar chart and bar plot in Python the same thing?

Yes. The terms are used interchangeably; in Matplotlib all of them are produced by bar (vertical) or its horizontal counterpart.

How do I put exact values on the bars?

Store the container returned by ax.bar and call ax.bar_label(container).

How do I draw grouped bars?

Use ax.grouped_bar in Matplotlib 3.11 or later, or offset several ax.bar calls as shown above.

What should error bars represent?

Matplotlib does not decide this. Compute the standard deviation, standard error or confidence interval yourself, pass it as yerr and name it in the caption.

Sources (official docs)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Bar Plot in Matplotlib: Syntax, Grouped Bars, Error Bars

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →