前言
本篇开始学习Matplotlib的常规用法,以及最佳实践帮助你掌握Matplotlib库。
一个简单的例子
创建一个图表(Figure),里面包含一个坐标轴(Axes)
# Create a figure containing a single axes.fig, ax = plt.subplots()# Plot some data on the axesax.plot([1, 2, 3, 4], [1, 4, 2, 3])plt.show()
Figure(相当于一个绘制窗口、或者是绘制组件),每个Figure包含一个Axes,Axes可以绘制x-y-z坐标轴的图形。以上调用创建一个二维的坐标图
坐标轴
图表组件
有些名词翻译成中文反而不好理解,所以后续对于重点名词不翻译,以下四个非常重要
(1) Figure
Figure保存所有的Axes记录,Axes由一系列的Artist组成。最简单的创建Figure的方式
fig = plt.figure() # an empty figure with no Axesfig, ax = plt.subplots() # a figure with a single Axesfig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of AxesAxes
(2) Axes
Axes是附着于Figure之上,通常包含两个Axis对象,可以对Axes上的数据进行拉伸操作。Axes可以通过set_title()函数改变名字。
(2) Axis(轴)
通过Locator决定点的位置,通过Formatter生成点的标签。
(4) Artist
所有Figure上可见的东西都是Artist(包括Figure, Axes, Axis, Text, Line2D, Patch)等。所有的Artist都是通过canvas进行绘制的,绝大部分的Artists都依附于Axes。
输入数据的种类
绘制函数都需要numpy.array或者numpy.ma.masked_array数组作为输入,或者可以传递到numpy.asarray的对象。一些和数组相似的类,比如pandas, dumpy.matrix是不能传递到绘制函数上的,它们都需要转化为numpy.array对象。
b = np.matrix([[1, 2], [3, 4]])b_asarray = np.asarray(b)
输出
[[1 2] [3 4]]
绘制函数也可以解析类似dict,numpy.recarray, pandas.DataFrame等可寻址的对象。
np.random.seed(19680801) # seed the random number generator.data = {'a': np.arange(50), 'c': np.random.randint(0, 50, 50), 'd': np.random.randn(50)}data['b'] = data['a'] + 10 * np.random.randn(50)data['d'] = np.abs(data['d']) * 100fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')ax.scatter(x='a', y='b', c='c', s='d', data=data)ax.set_xlabel('entry a')ax.set_ylabel('entry b');
scatter()函数中x和y表示坐标位置,c表示坐标点的颜色,s表示坐标点的大小,data表述传递进来的数据。
传递数据
编码风格
有两种使用Matplotlib绘制的方式:
使用面向对象的方式
x = np.linspace(0, 2, 100) # Sample data.# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')ax.plot(x, x, label='linear') # Plot some data on the axes.ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...ax.plot(x, x**3, label='cubic') # ... and some more.ax.set_xlabel('x label') # Add an x-label to the axes.ax.set_ylabel('y label') # Add a y-label to the axes.ax.set_title("Simple Plot") # Add a title to the axes.ax.legend() # Add a legend.plt.show()
绘制三条线条
编码风格
使用pyplot方式绘制
x = np.linspace(0, 2, 100) # Sample data.plt.figure(figsize=(5, 2.7), layout='constrained')plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.plt.plot(x, x**2, label='quadratic') # etc.plt.plot(x, x**3, label='cubic')plt.xlabel('x label')plt.ylabel('y label')plt.title("Simple Plot")plt.legend()plt.show()
得到的结果和面向对象一样的,还有第三种绘制方式,后续会介绍。Matplotlib的示例中面向对象的方式和pyplot的方式都会使用。通常来说建议使用面向对象的方式,但是pyplot的方式可以更快递完成交互工作。
如果有代码重复的地方,可以编写帮助函数,比如重复绘制一些点:
def my_plotter(ax, data1, data2, param_dict): """ A helper function to make a graph. """ out = ax.plot(data1, data2, **param_dict) return out
传递不同的数据调用帮助函数绘制
data1, data2, data3, data4 = np.random.randn(4, 100) # make 4 random data setsfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))my_plotter(ax1, data1, data2, {'marker': 'x'})my_plotter(ax2, data3, data4, {'marker': 'o'})plt.show()
marker是点的标记形式
帮助函数
留言与评论(共有 0 条评论) “” |