Menu
CoddyTech

Plotting a DataFrame

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 47 of 60.

A table already holds the numbers a chart needs. By the end of this chapter, one table will give you this:

Two charts from one bookshop table: a line of customers per day over two weeks, and a histogram of daily sales

It starts with one call. df.plot takes two column names: x= across, y= up:

sales = pd.DataFrame({"day": [1, 2, 3, 4, 5], "cups": [12, 18, 15, 25, 30]})
fig, ax = plt.subplots()
sales.plot(x="day", y="cups", ax=ax)
ax.set_title("Lemonade Sales")
plt.show()

This draws the chart below. pandas labels the x axis day and names the line cups in a legend, by itself:

A line of lemonade cups over five days, climbing from 12 to 30 with a dip on day 3, x axis labelled day, legend cups

ax=ax puts the line on your axes. Without it, pandas makes a new figure, and your title lands on an empty chart.

challenge icon

Challenge

Medium

A river gauge logged the water level every hour through a stormy night. river.csv has hour, level_cm and rain_mm.

  1. Create a figure and axes.
  2. Use river.plot to draw level_cm against hour on those axes.
  3. Title it River Level, label the y axis Level (cm), and show it.

Yours should look like this one, from a gauge upstream:

A line titled River Level, x axis hour from 0 to 12, y axis Level (cm), rising from 60 to a peak of 88 at hour 7, then easing to 75, legend level_cm

Your program prints nothing: Coddy checks your chart and describes it in the output.

Try it yourself

import pandas as pd
import matplotlib.pyplot as plt

river = pd.read_csv("river.csv")

# Write your code below
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