How to write text above the bars on a bar plot (Python Matplotlib)?

MatplotlibPythonData Visualization

To write text above the bars on a bar plot, we can take the following steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Create lists of year, population and x. Initialize a width variable.
  • Create a figure and a set of subplots using subplots() method.
  • Set ylabels, title, xtickas and xticklabels.
  • Plot the bars using bar() method with x, population and width data.
  • Iterate the bar patches and place text at the top of the bars using text() method.
  • To display the figure, use show() method.

Example

from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09,
439.23, 548.16, 683.33, 846.42, 1028.74]
x = np.arange(len(years)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
ax.set_ylabel('Population(in million)')
ax.set_title('Years')
ax.set_xticks(x)
ax.set_xticklabels(years)
pps = ax.bar(x - width / 2, population, width, label='population')
for p in pps:
height = p.get_height()
ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10,
s="{}".format(height),
ha='center')
plt.show()

Output

raja
Published on 01-Jun-2021 11:46:17
Advertisements