Basic Matplotlib Exercises

See also: Matplotlib API

See also: Matplotlib.pyplot Documentation

See also: Matplotlib Examples



In [1]:
# 1. Import matplotlib. Import matplotlib.pyplot as plt. Import numpy as np. 

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

In [2]:
# 2. Use the '%matplotlib inline' magic method. Run matplotlib.style.use('fivethirtyeight')

%matplotlib inline
matplotlib.style.use('fivethirtyeight')

In [3]:
# 3. Create a range of x values with np.arange(-10, 10, .5)

x = np.arange(-10, 10, .5)

In [5]:
# 4. Write a function that squares your x value. Make a list of y values that is the y = your_function(x).

def square(x):
    output = x ** 2
    return output

y = [square(x_item) for x_item in x] # list comprehension

In [6]:
# 5. Use plt.plot() with your x and y values to make a line graph

plt.plot(x, y)


Out[6]:
[<matplotlib.lines.Line2D at 0x78bcc50>]

In [7]:
# 6. Use plt.scatter() with your x and y values to make a scatter graph.

plt.scatter(x, y)


Out[7]:
<matplotlib.collections.PathCollection at 0x7cab4a8>

In [8]:
# 7. Use plt.subplots() and tuple unpacking to get your figure and axes. Assign to fig and ax.

fig, ax = plt.subplots()



In [9]:
# 8. Get your axes by plt.gca() (get current axis). Get your figure by plt.gcf() (get current figure).

axes = plt.gca()
fig = plt.gcf()



In [10]:
# 9. Use your axes to change the x and y limits of the graph. Show the result.

axes.set_xlim(-5, 5)
axes.set_ylim(-5, 5)
fig


Out[10]:

In [11]:
# 10. Replot your X and Y scatter graph.

axes.scatter(x, y)
fig


Out[11]:

In [12]:
# 10. Use your axes to set the title of the graph, the x axis labels, and the y axis labels.

axes.set_title('My graph')
axes.set_xlabel('My X Axis')
axes.set_ylabel('My Other Axis')

fig


Out[12]:

In [13]:
# 11. Plot a second line on the graph of y=1.

axes.plot([-5, 5], [1,1])
fig


Out[13]:

In [14]:
# 12. Save your graph using your figure's savefig() method to the data folder.

fig.savefig('data/matplotlib_fig.png')