Matplotlib bar() / barh() Function


Matplotlib 参考文档Matplotlib Reference Documentation

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

Bar charts are used to display the quantitative comparison of categorical data, where each category is represented by a bar whose length 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

ParameterTypeDescription
x / yarray-likeThe position coordinates of the bars (x for vertical, y for horizontal)
height / widtharray-likeThe height (vertical) or width (horizontal) of the bars, i.e., the data values
width(bar)/ height(barh)float or array-likeThe width/height of the bars, default 0.8
bottom / leftfloat or array-likeThe starting position of the bottom of the bars, default 0. Can be used to draw stacked bar charts.
alignstrAlignment of the bars relative to the x/y coordinates: 'center' (default) or 'edge'
colorcolor or listBar color, can be a single color or a list of colors
edgecolorcolorBar border color
linewidth / lwfloatBar border width
tick_labelarray-likeTick labels for the bars, corresponding one-to-one with the x positions
labelstrLegend label (used for grouped bar charts)
alphafloatTransparency
hatchstrFill patterns: '/', '\\', '|', '-', '+', 'x', 'o', '*'

bar_label() Additional 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)

Both bar() and barh() return aBarContainerobject, 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 bar chart
bars = ax.bar(categories, values,
              color=['#3498db', '#e74c3c', '#f39c12', '#2E7DCC', '#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                  # 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='#2E7DCC', edgecolor='white')
# Second layer of bars (stacked on top of the first layer)
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()

FAQ

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

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

barh(y, width): y is the position, 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 in a grouped bar chart next to each other?

willwidthSet it to the reciprocal of the total width of each group of bars, and usealign='edge'。


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions