Easy Tutorial
❮ Matplotlib Grid Matplotlib Pyplot ❯

Matplotlib Bar Chart

We can use the bar() method from pyplot to create bar charts.

The syntax for the bar() method is as follows:

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

Parameter Description:

x: Float array, the x-axis data for the bar chart.

height: Float array, the heights of the bar chart.

width: Float array, the widths of the bar chart.

bottom: Float array, the y-coordinates of the base, default is 0.

align: Alignment of the bar chart with the x-coordinates, 'center' centers the bars on the x positions, which is the default. 'edge' aligns the left edge of the bars with the x positions. To align the right edge of the bars, you can pass a negative width value with align='edge'.

kwargs: Other parameters.

Here is a simple example using bar() to create a bar chart:

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["tutorialpro-1", "tutorialpro-2", "tutorialpro-3", "C-tutorialpro"])
y = np.array([12, 22, 6, 18])

plt.bar(x, y)
plt.show()

The result is displayed as follows:

Vertical bar charts can be set using the barh() method:

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["tutorialpro-1", "tutorialpro-2", "tutorialpro-3", "C-tutorialpro"])
y = np.array([12, 22, 6, 18])

plt.barh(x, y)
plt.show()

The result is displayed as follows:

Setting the color of the bar chart:

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["tutorialpro-1", "tutorialpro-2", "tutorialpro-3", "C-tutorialpro"])
y = np.array([12, 22, 6, 18])

plt.bar(x, y, color="#4CAF50")
plt.show()

The result is displayed as follows:

Customizing the color of each bar:

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["tutorialpro-1", "tutorialpro-2", "tutorialpro-3", "C-tutorialpro"])
y = np.array([12, 22, 6, 18])

plt.bar(x, y, color=["#4CAF50", "red", "hotpink", "#556B2F"])
plt.show()

The result is displayed as follows:

Setting the width of the bar chart, the bar() method uses width to set it, and the barh() method uses height to set it:

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["tutorialpro-1", "tutorialpro-2", "tutorialpro-3", "C-tutorialpro"])
y = np.array([12, 22, 6, 18])

plt.bar(x, y, width=0.1)
plt.show()

The result is displayed as follows:

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["tutorialpro-1", "tutorialpro-2", "tutorialpro-3", "C-tutorialpro"])
y = np.array([12, 22, 6, 18])

plt.barh(x, y, height=0.1)
plt.show()

The result is displayed as follows:

❮ Matplotlib Grid Matplotlib Pyplot ❯