# import matplotlib import matplotlib as mpl # check the version of matplotlib mpl.__version__ # import the main plotting package with the usual abbreviation plt import matplotlib.pyplot as plt # Sets the plotting style to seaborn plt.style.use("seaborn") # Sets the font to be serif in all plots. mpl.rcParams['font.family'] = "serif"
2.1 一维数据集
最基础的,然而也是最强大的绘图函数是 plt.plot(),它需要两个组数据:
x 值:横坐标
y 值:纵坐标
注意 x 和 y 的值必须能够匹配,例如:
import numpy as np np.random.seed(1000) y = np.random.standard_normal(20) x = np.arange(len(y)) plt.plot(x, y)
# Increases the size of the figure. plt.figure(figsize=(10,6) plt.plot(y.cumsum(), "b", lw = 1.5) # Plots the data as red (thick) dots plt.plot(y.cumsum(), "ro") # Places a label on the x-axis. plt.xlabel("index") # Places a label on the y-axis. plt.ylabel("value") # places a title plt.title("A simple plot")
2.2. 二维数据集
首先让我们生成一些数据:
y = np.random.standard_normal((20,2)).cumsum(axis=0)
采用相同的方法进行绘制:
# Increases the size of the figure. plt.figure(figsize=(10,6)) plt.plot(y, lw = 1.5) # Plots the data as red (thick) dots plt.plot(y, "ro") # Places a label on the x-axis. plt.xlabel("index") # Places a label on the y-axis. plt.ylabel("value") # places a title plt.title("A simple plot")
当然我们可以加上图例 plt.legend():
plt.figure(figsize=(10, 6))
# Defines labels for the data subsets. plt.plot(y[:, 0], lw=1.5, label='1st') plt.plot(y[:, 1], lw=1.5, label='2nd') plt.plot(y, 'ro') # Places a legend in the “best” location plt.legend(loc=0) plt.xlabel('index') plt.ylabel('value') plt.title('A Simple Plot')
假设 y 的第一列为:
y[:,0] = y[:,0]*100
plt.figure(figsize=(10, 6)) # Defines labels for the data subsets. plt.plot(y[:, 0], lw=1.5, label='1st') plt.plot(y[:, 1], lw=1.5, label='2nd') plt.plot(y, 'ro') # Places a legend in the “best” location plt.legend(loc=0) plt.xlabel('index') plt.ylabel('value') plt.title('A Simple Plot')
为此我们可以将 y 的两列分别采用不同的轴予以体现,或者将这两列绘制在两个子图上面。一方面,对于第一种方式,我们可以通过如下的方式予以实现:
# define the fig and axis objects fig, ax1 = plt.subplots() plt.plot(y[:,0], "b", lw = 1.5, label = "1st") plt.plot(y[:,0], 'r^') plt.legend(loc = 8) plt.xlabel("index") plt.ylabel(("value 1st")) plt.title('a simple plot') # Creates a second axis object that shares the x-axis. ax2 = ax1.twinx() plt.plot(y[:,1], 'g', lw = 1.5, label = "2nd") plt.plot(y[:,1], "ro") plt.legend(loc = 0) plt.ylabel("value 2nd")
另一方面对于第二种方式,我们可以采用如下方式:
plt.figure(figsize=(10,6)) # plt.subplot() takes as arguments three integers for # numrows, numcols, and fignum (either separated by commas or not). plt.subplot(211) plt.plot(y[:,0], "b", lw = 2, label = "1st") plt.plot(y[:,0], 'r>') plt.legend(loc = 0) plt.ylabel("value 1st") plt.title("a simple plot with two y axes") plt.subplot(2,1,2) plt.plot(y[:,1], "g", lw = 2, label = "2nd") plt.plot(y[:,1], 'r) plt.legend(loc = 0) plt.ylabel("value 2nd") plt.xlabel("index")