Week 5¶

  • Define a figure and axes variables:

    my_fig = plt.figure()
    ax = plt.axes()
    ax.plot(x,y)
    ax.set_xlabel('horizontal label')
    ax.set_ylabel('vertical label')
    ax.set_title('my title')
    ax.set_xlim(0, 100)
    ax.axvline(2)
    ax.axhline(6,color='r')

Defining a figure with plt.figure() allows you to work on multiple figures at one time, each assigned to a different variable, i.e.:

In [ ]:
import matplotlib.pyplot as plt 


fig1 = plt.figure()
fig2 = plt.figure()
fig3 = plt.figure()
<Figure size 640x480 with 0 Axes>
<Figure size 640x480 with 0 Axes>
<Figure size 640x480 with 0 Axes>

np.diff()¶

np.diff calculates the differences between adjacent values in an array:

In [ ]:
output = np.diff(np.array([1,1,2,3,5,8,13]))
output
array([0, 1, 1, 2, 3, 5])

(1-1 = 0, 2-1 = 1, 3-2 = 1, etc.)

Notice how many values are in each array above.

Plotting labels & legends:¶

When you call a plotting function, if you define a label for your line, bar, etc., and call the plt.legend() function, the legend will automatically populate with the labels for each line:

plt.plot(x,y, label = "my_line")
plt.legend()

This is particularly useful when plotting many lines. If you have a list of your line names, you can iterate through them with a for-loop:

line_names = ["line1", "line2" ,"line3"]
for i in lines:
plt.plot(lines[i], label = line_names[i])

While Loops:¶

Format:
while <condition is met>:
do function

In [ ]:
i = 0
while i < 7:
    i = i+1
    print(i)
1
2
3
4
5
6
7