2

What is the most simple way to label all the sections?

x = ['A', 'B', 'C', 'D']
y1 = np.array([2, 4, 5, 1])
y2 = np.array([1, 0, 2, 3])
y3 = np.array([4, 1, 1, 1])

plt.bar(x, y1, color='#d67ed0')
plt.bar(x, y2, color='#e6ad12', bottom=y1)
plt.bar(x, y3, color='#13c5ed', bottom=y1+y2)

plt.show()

Like "A"-Violet labeled as "2" on the plot

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Artyom P.
  • 21
  • 4

1 Answers1

1

The easiest way to label each colored section is by using a legend. Assign a category to each color in the bar using the label argument in the plt.bar function. Then use the plt.legend() function at the end of the code to display the legend.

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

x = ['A', 'B', 'C', 'D']
y1 = np.array([2, 4, 5, 1])
y2 = np.array([1, 0, 2, 3])
y3 = np.array([4, 1, 1, 1])

# increase figure size
plt.figure(figsize = (10,7))

# add labels to each color
plt.bar(x, y1, color='#d67ed0', label = 'Cars')
plt.bar(x, y2, color='#e6ad12', bottom=y1, label = 'Buses')
plt.bar(x, y3, color='#13c5ed', bottom=y1+y2, label = 'Trains')
plt.legend(loc = 1, fontsize = 18)

plt.show()

enter image description here

Aaron Horvitz
  • 166
  • 1
  • 6