100 days of code: Day 24 - graphing squares

Last modified on 2020-07-02

Source: 100-days-of-code.

Yesterday’s graph of x- and y-coordinates was inaccurate because plot() assumes the first data point corresponds to an x-coordinate value of 0, but in this case our first x-value is 1. Override the default by assigning the input and output values used …

import matplotlib.pyplot as plt

inputs = []
squares = []

for i in range(1, 11):
    inputs.append(i)
    squares.append(i**2)

# Using built-in styles. Find styles with `plt.style.available`.
plt.style.use('seaborn')

# subplots() can generate one or more plots in the same figure. Variable 'fig'
# represents the entire figure or collection of plots generated. Variable 'ax' 
# represents a single plot in the figure.
fig, ax = plt.subplots()

# plot() assumes the first data point corresponds to an x-coordinate
# value of 0, but in this case our first x-value is 1. Override default
# by assigning the input and output values used.
ax.plot(inputs, squares, linewidth=3) 

# Set chart title and label axes.
ax.set_title("Square Numbers", fontsize=18)
ax.set_xlabel("Value", fontsize=12)
ax.set_ylabel("Square of Value", fontsize=12)

# Set size of tick labels
ax.tick_params(axis='both', labelsize=12)

plt.show()

Yesterday’s graph …

mpl_squares-figure_1

New and improved graph …

mpl_squares-figure_2

Happy hacking!