Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib bar() / barh() Function

Matplotlib bar() / barh() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

bar() Used to draw vertical bar charts,barh() Used to draw horizontal bar charts.

Bar charts are used to show comparisons of quantities across categorical data, with each category represented by a bar whose height indicates its value.

Function definition

bar() - vertical bar chart

matplotlib.pyplot.bar(x, height, width=0.8, bottom=0, *, align='center',
    **kwargs)

barh() - horizontal bar chart

matplotlib.pyplot.barh(y, width, height=0.8, left=0, *, align='center',
    **kwargs)

Axes interface

Axes.bar(x, height, width=0.8, bottom=0, *, align='center', **kwargs)
Axes.barh(y, width, height=0.8, left=0, *, align='center', **kwargs)

Parameter Description

Parameters Type Description
x / y array-like The position coordinates of the bars (x for vertical, y for horizontal)
height / width array-like The height of the bars (vertical) or width (horizontal), i.e., the data values
width(bar)/ height(barh) float or array-like The width/height of the bars, default 0.8
bottom / left float or array-like The starting position of the bottom of the bars, default 0. Can be used to draw stacked bar charts
align str The alignment of the bars with the x/y coordinates: 'center' (default) or 'edge'
color color or list Bar color, can be a single color or a list of colors
edgecolor color Bar edge color
linewidth / lw float Bar edge width
tick_label array-like Tick labels for the bars, corresponding one-to-one with the x positions
label str Legend labels (for grouped bar charts)
alpha float Transparency
hatch str Fill patterns: '/', '', '|', '-', '+', 'x', 'o', '*'

bar_label() supplementary notes

bar_label() Used to display value labels directly on the bars.

Axes.bar_label(container, labels=None, *, fmt=None, label_type='edge',
    padding=0, **kwargs)

bar() and barh() return a BarContainer object, which can be passed to bar_label() to add value labels. This is the recommended approach in Matplotlib 3.4+.


Usage examples

Example 1: basic vertical bar chart

Example

import

matplotlib.

pyplot

as

plt

Category labels and data

categories

=

[

'Python'

,

'Java'

,

'JavaScript'

,

'C++'

,

'Go'

]

values

=

[

85

,

72

,

68

,

55

,

42

]

fig

,

ax

=

plt.

subplots

(

layout

=

'constrained'

)

Draw a bar chart

bars

=

ax.

bar

(

categories

,

values

,

              color

=

[

'#3498db'

,

'#e74c3c'

,

'#f39c12'

,

'#2ecc71'

,

'#9b59b6'

]

,

              edgecolor

=

'white'

,

linewidth

=

1

)

Display values on the bars

ax.

bar_label

(

bars

,

fmt

=

'%d'

,

padding

=

3

)

ax.

set_title

(

'Programming Language Popularity'

)

ax.

set_ylabel

(

'Score'

)

ax.

set_ylim

(

0

,

100

)

ax.

grid

(

axis

=

'y'

,

alpha

=

0.3

)

plt.

show

(

)

Example 2: grouped bar chart

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Grouped data

labels

=

[

'Q1'

,

'Q2'

,

'Q3'

,

'Q4'

]

product_a

=

[

120

,

135

,

148

,

162

]

product_b

=

[

90

,

105

,

115

,

130

]

x

=

np.

arange

(

len

(

labels

)

)

 

x positions: [0, 1, 2, 3]

width

=

0.35

                 

The width of each bar

fig

,

ax

=

plt.

subplots

(

layout

=

'constrained'

)

First group of bars (offset -width/2)

bars1

=

ax.

bar

(

x - width/

2

,

product_a

,

width

,

               label

=

'Product A'

,

color

=

'steelblue'

,

edgecolor

=

'white'

)

Second group of bars (offset +width/2)

bars2

=

ax.

bar

(

x + width/

2

,

product_b

,

width

,

               label

=

'Product B'

,

color

=

'coral'

,

edgecolor

=

'white'

)

Add value labels

ax.

bar_label

(

bars1

,

padding

=

3

,

fmt

=

'%d'

)

ax.

bar_label

(

bars2

,

padding

=

3

,

fmt

=

'%d'

)

ax.

set_title

(

'Quarterly Sales Comparison'

)

ax.

set_ylabel

(

'Sales (units)'

)

ax.

set_xticks

(

x

)

ax.

set_xticklabels

(

labels

)

ax.

legend

(

)

ax.

grid

(

axis

=

'y'

,

alpha

=

0.3

)

plt.

show

(

)

Example 3: stacked bar chart

Example

import

matplotlib.

pyplot

as

plt

categories

=

[

'Jan'

,

'Feb'

,

'Mar'

,

'Apr'

,

'May'

]

income

=

[

5000

,

5200

,

4800

,

5500

,

6000

]

expense

=

[

3000

,

3500

,

3200

,

4000

,

4200

]

fig

,

ax

=

plt.

subplots

(

layout

=

'constrained'

)

First layer of bars (bottom)

bars_income

=

ax.

bar

(

categories

,

income

,

                     label

=

'Income'

,

color

=

'#2ecc71'

,

edgecolor

=

'white'

)

Second layer of bars (stacked on top of the first)

bars_expense

=

ax.

bar

(

categories

,

expense

,

bottom

=

income

,

                      label

=

'Expense'

,

color

=

'#e74c3c'

,

edgecolor

=

'white'

)

Add labels

ax.

bar_label

(

bars_income

,

label_type

=

'center'

,

fmt

=

'$%d'

)

ax.

bar_label

(

bars_expense

,

label_type

=

'center'

,

fmt

=

'$%d'

)

ax.

set_title

(

'Stacked Bar Chart: Monthly Finance'

)

ax.

set_ylabel

(

'Amount ($)'

)

ax.

legend

(

)

ax.

grid

(

axis

=

'y'

,

alpha

=

0.3

)

plt.

show

(

)

Example 4: horizontal bar chart (barh)

Example

import

matplotlib.

pyplot

as

plt

tasks

=

[

'Task A'

,

'Task B'

,

'Task C'

,

'Task D'

,

'Task E'

]

hours

=

[

12.5

,

8.0

,

15.3

,

6.2

,

10.8

]

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

4

)

,

layout

=

'constrained'

)

Horizontal bar chart

bars

=

ax.

barh

(

tasks

,

hours

,

               color

=

'#3498db'

,

edgecolor

=

'white'

,

height

=

0.6

)

Add labels at the end of the bars

ax.

bar_label

(

bars

,

fmt

=

'%.1f h'

,

padding

=

5

)

ax.

set_title

(

'Task Completion Time (Horizontal Bar)'

)

ax.

set_xlabel

(

'Hours'

)

ax.

invert_yaxis

(

)

 

Invert the y-axis so the first category is at the top

ax.

grid

(

axis

=

'x'

,

alpha

=

0.3

)

plt.

show

(

)


Common questions

What is the axis correspondence for bar() and barh()?

bar(x, height): x is the position, and height determines the bar height (vertical direction).

barh(y, width): y is the position, and width determines the bar width (horizontal direction).

Note the different parameter names: bar uses height, barh uses width to represent the data values.

How to make the bars of a grouped bar chart sit close together?

data to the child component via width Set it to the reciprocal of the total width of each group of bars, and use align='edge'。

Matplotlib Reference Documentation Matplotlib Reference Documentation