Practice#1: Line plot
import matplotlib.pyplot as plt %matplotlib inline # 3 basic arguments in the following order: (x, y, format) plt.plot([1,2,3,4,5], [1,2,3,6,10], "bx-")
Practice#2: Scatter plot
import matplotlib.pyplot as plt %matplotlib inline from sklearn.datasets import load_boston # load boston dataset # with features and house prices dataset = load_boston() X = dataset["data"] y = dataset["target"] # crim rate vs. house price plt.scatter(X[:,0], y, s=10) plt.xlabel(dataset["feature_names"][0]) plt.ylabel("house price")
Practice#3: Box plot
fig, ax = plt.subplots(1, figsize=(9,6)) norm_dist_1 = np.random.normal(100, 10, 200) norm_dist_2 = np.random.normal(40, 30, 200) norm_dist_3 = np.random.normal(70, 20, 200) norm_dist_4 = np.random.normal(90, 25, 200) data_to_plot = [norm_dist_1, norm_dist_2, norm_dist_3, norm_dist_4] ax.boxplot(data_to_plot) ax.set_xticklabels(['Sample1', 'Sample2', 'Sample3', 'Sample4']) plt.show()
Practice#4: Objective-oriented way of using matplotlib
fig, axes = plt.subplots(1, 2) axes[0].plot(x, y, 'ro--') axes[1].plot(x, y^2, 'g+-') axes[0].set_xlabel('x') axes[0].set_ylabel('y') axes[0].set_title('y plot') axes[1].set_xlabel('x') axes[1].set_ylabel('$y^2$') axes[1].set_title('$y^2$ plot')
Here, fig denotes the whole canvas, and axes denote a set of figures you want to use, where the params (1, 2) indicate that you want to use 1 * 2 = 2 figures in total.
In order to access each figure and actually plot on those figures, you can use their indices, e.g., axes[0] indicates the first figure and axes[1] refers to the second figure in your canvas.
Afterwards, you can use an objective-oriented manner to plot and add details on each figure, e.g., add title to the first figure by using axes[0].set_title('blabla').
Using this way, we can obtain full control over those figures and even use for loops for plotting as many figures as we want.