Menu
CoddyTech

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:

Two charts side by side: a bar chart of average rain for each weekday, Thursday the wettest, and a histogram of daily rain where most days have almost none

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()

A bar chart titled Scoops Sold with four bars: Chocolate 42, Vanilla 27, Mint 15, Mango 21

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 icon

Challenge

Medium

48 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:

  1. Turn the counts into percent, rounded to 1 place (12 of 48 is 25.0).
  2. Draw them as bars: Walk, Bike, Bus, Car.
  3. Label the axis up Students (%).

Yours should look like this, from a smaller school:

A bar chart titled Getting to School with four bars in percent: Walk 26.7, Bike 13.3, Bus 40, Car 20

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler