Bar Charts
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 26 of 60.
This chapter turns data into summaries. By its end, you will build a two-chart report like this one:
It starts with bars. Flavors have no order, so a line from one to the next means nothing. ax.bar(categories, values) draws one bar per category:
flavors = ["Chocolate", "Vanilla", "Mint", "Mango"]
sold = [42, 27, 15, 21]
fig, ax = plt.subplots()
ax.bar(flavors, sold)
ax.set_title("Scoops Sold")
ax.set_ylabel("Scoops")
plt.show()Bars start at 0, so heights compare directly: chocolate's 42 is twice mango's 21. Before training a model, bars of how often each answer appears show whether one dominates.
Challenge
Medium48 students said how they get to school. counts holds the answers per code: 1 walk, 2 bike, 3 bus, 4 car. To compare schools, chart shares:
- Turn the counts into percent, rounded to 1 place (12 of 48 is
25.0). - Draw them as bars:
Walk,Bike,Bus,Car. - Label the axis up
Students (%).
Yours should look like this, from a smaller school:
Your program prints nothing. Coddy describes your bars in the output.
Try it yourself
import numpy as np
import matplotlib.pyplot as plt
# 1 = walk, 2 = bike, 3 = bus, 4 = car
answers = np.array([1, 3, 1, 4, 3, 3, 4, 3, 4, 4, 3, 4, 4, 4, 3, 3,
2, 2, 2, 1, 1, 3, 1, 1, 1, 2, 3, 3, 1, 3, 2, 1,
3, 4, 3, 3, 1, 1, 1, 2, 3, 1, 3, 4, 4, 3, 2, 4])
# Returns an array: how many values equal each code from 1 to 4
def count_codes(values):
counts = []
for code in range(1, 5):
counts.append((values == code).sum())
return np.array(counts)
counts = count_codes(answers)
fig, ax = plt.subplots()
ax.set_title("Getting to School")
# Write your code below
# Don't change the line below
plt.show()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler