Week 6:¶

Subsetting arrays with conditionals:

In [ ]:
#Define an array
arr = np.array([[2,4,1,7],[9,4,7,6],[1,2,1,5],[4,8,8,1]])
print(arr, "\n")

#Make a selection based on a conditional (values greater than 5)
conditional_selection = arr > 5
print(conditional_selection, "\n")

#Subset the original array with the selection array
subset_arr = arr[conditional_selection]
print(subset_arr) # This returns an array of all the values from the original array that are greater than 5
[[2 4 1 7]
 [9 4 7 6]
 [1 2 1 5]
 [4 8 8 1]] 

[[False False False  True]
 [ True False  True  True]
 [False False False False]
 [False  True  True False]] 

[7 9 7 6 8 8]

np.argmax(), np.argmin(), np.argsort()¶

In [ ]:
np.argmax(arr) # Returns the index of the max value in an array (reads a 2D array like 1D), 
                #i.e. the 4th index is the first value of the second row
4
In [ ]:
np.argmax(arr, axis = 1) # gives the index of the max value for each row
array([3, 0, 3, 1])
In [ ]:
np.argmax(arr, axis = 0) # gives the index of the max value for each column
array([1, 3, 3, 0])

np.argmin() behaves the same, but finds the index of the min

np.argsort() returns the indexes of the array if it were to be sorted:

In [ ]:
print(arr[0])
print(np.argsort(arr[0]))
[2 4 1 7]
[2 0 1 3]

Read this as: the sorted order of the first row is the [2] value, then the [0] value, then the [1] value, then the [3] value.

A for-loop to demonstrate:

In [ ]:
for i in np.argsort(arr[0]):
    print(arr[0,i])
1
2
4
7

Creating subplots:¶

  • Defining figure and figuresize
    fig=plt.figure(figsize=(10,3))
  • Making subplots:
fig,ax=plt.subplots()
fig, (ax1,ax2)=plt.subplots(1,2)
fig.savefig('myfig.pdf')
  • Methods of the axis class:
ax.xticks
ax.yticks
ax.set_ylim
ax.set_xlim
ax.xticklabels
ax.yticklabels
ax.text
ax.spines
ax.set_aspect
  • Useful reference: Matplotlib Gallery examples
    For instance, subplots example
In [ ]:
import numpy as np
import matplotlib.pyplot as plt

arr1 = np.array([[1,2,3,4,5],[5,7,2,5,5]])
arr2 = np.array([[1,2,3,4,5],[1,1,5,9,9]])


fig, ax = plt.subplots(1,3) # Defines a new figure and axes, gives dimensions for subplot grid: 1 row, 2 columns
ax[0].scatter(arr1[0],arr1[1])
ax[1].scatter(arr2[0],arr2[1])
ax[2].scatter(arr1[0],arr1[1])
ax[2].scatter(arr2[0],arr2[1])
ax[0].set_ylabel('y axis')
for axis in ax:
    axis.set_xlim(-1,10)
    axis.set_ylim(0,10)
    axis.set_xlabel('x axis')
    axis.spines['top'].set_visible(False)
    axis.spines['right'].set_visible(False)
for i in range(1,3):
    ax[i].spines['top'].set_visible(False)
    ax[i].spines['right'].set_visible(False)
    ax[i].spines['left'].set_visible(False)
    ax[i].set_yticks([])
fig.tight_layout() # Generic statement for keeping labels and axes from overlapping
No description has been provided for this image