Example 1: bar labeling in matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
x = ['Nuclear', 'Hydro', 'Gas', 'Oil', 'Coal', 'Biofuel']
energy = [5, 6, 15, 22, 24, 8]
x_pos = [i for i, _ in enumerate(x)]
plt.bar(x_pos, energy, color='green')
plt.xlabel("Energy Source")
plt.ylabel("Energy Output (GJ)")
plt.title("Energy output from various fuel sources")
plt.xticks(x_pos, x)
plt.show()
Example 2: adding labels to histogram bars in matplotlib
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
freq_series = pd.Series(frequencies)
y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300)
rects = ax.patches
for rect in rects:
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
space = 5
ha = 'left'
if x_value < 0:
space *= -1
ha = 'right'
label = "{:.1f}".format(x_value)
plt.annotate(
label,
(x_value, y_value),
xytext=(space, 0),
textcoords="offset points",
va='center',
ha=ha)
plt.savefig("image.png")
Example 3: Grouped bar chart with labels
fig, ax = plt.subplots(figsize=(12, 8))
x = np.arange(len(df.job.unique()))
bar_width = 0.4
b1 = ax.bar(x, df.loc[df['sex'] == 'men', 'count'],
width=bar_width)
b2 = ax.bar(x + bar_width, df.loc[df['sex'] == 'women', 'count'],
width=bar_width)