How to add value labels on a bar chart
bar-chart, matplotlib, pandas, python, seaborn
Solution
Firstly `freq_series.plot` returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as `ax` rather than `fig` to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the `ax.patches` member. Then you can use the technique demonstrated in this `matplotlib` gallery example to add the labels using the `ax.text` method.
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)
x_labels = [
108300.0,
110540.0,
112780.0,
115020.0,
117260.0,
119500.0,
121740.0,
123980.0,
126220.0,
128460.0,
130700.0,
]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind="bar")
ax.set_title("Amount Frequency")
ax.set_xlabel("Amount ($)")
ax.set_ylabel("Frequency")
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = [f"label{i}" for i in range(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(
rect.get_x() + rect.get_width() / 2, height + 5, label, ha="center", va="bottom"
)
plt.show()
This produces a labeled plot that looks like:
Problem
I'm creating a bar chart, and I can't figure out how to add value labels on the bars (in the center of the bar, or just above it). I believe the solution is either with 'text' or 'annotate', but I: a) don't know which one to use (and generally speaking, haven't figured out when to use which). b) can't see to get either to present the value labels. Here is my code: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt pd.set_option('display.mpl_style', 'default') %matplotlib inline # Bring some raw data. frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1] # In my original code I create a series and run on that, # so for consistency I create a series from the list. freq_series = pd.Series(frequencies) x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 121740.0, 123980.0, 126220.0, 128460.0, 130700.0] # Plot the figure. plt.figure(figsize=(12, 8)) fig = freq_series.plot(kind='bar') fig.set_title('Amount Frequency') fig.set_xlabel('Amount ($)') fig.set_ylabel('Frequency') fig.set_xticklabels(x_labels) ``` How can I add value labels on the bars (in the center of the bar, or just above it)?