声明1:此为我的个人学习笔记,转载请附原文链接。
声明2:英语水平扎实的同学学Matplotlib库建议到Matplotlib 3.3.2 documentation
感觉直接读英文文档吃力的我有两个建议:
1.下载浏览器插件,全屏翻译,辅助学习。(但切记不要看着翻译学习!只起辅助理解作用;还有不要深钻单个英文单词的意思,学技术捎带学英语,主次关系要明确!)
2.可以先看我的笔记入了门,然后再参照原文档深入学习或者从实践中学习,需用什么图就学什么。
目录
1.A simple example
The most simple way of creating a figure with an axes is using pyplot.subplots. We can then use Axes.plot to draw some data on the axes:
创建带有轴的图形最简单的方法是使用 pyplot.subplot。然后我们可以使用 Axes.plot 在轴上绘制一些数据:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots() # Create a figure containing a single axes;axes:坐标轴,axis:坐标轴线
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes.
plt.show()
运行结果:
2.Parts of a figure(介绍figure的各部分)
了解一幅figure中的每个part的英文表示
Figure:The whole figure. The figure keeps track of all the child Axes, a smattering of ‘special’ artists (titles, figure legends, etc), and the canvas. (Don’t worry too much about the canvas, it is crucial as it is the object that actually does the drawing to get you your plot, but as the user it is more-or-less invisible to you). A figure can contain any number of Axes, but will typically have at least one.
我的理解是:Figure就是整个画布,包含轴和一些别的比较特别的Artist(标题,分类图示等),一般来说一个figure至少有一个Axes。
Axes:This is what you think of as ‘a plot’, it is the region of the image with the data space. A given figure can contain many Axes, but a given Axes object can only be in one Figure. The Axes contains two (or three in the case of 3D) Axis objects (be aware of the difference between Axes and Axis) which take care of the data limits (the data limits can also be controlled via the axes.Axes.set_xlim() and axes.Axes.set_ylim() methods). Each Axes has a title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).
我的理解是:Axes就是figure内的一个区域,只不过这个区域不是空白的,是由轴与实现包围的。一个figure可以包含很多axes,但某个给定的axes只能在一个figure中。
Axis:These are the number-line-like objects. They take care of setting the graph limits and generating the ticks (the marks on the axis) and ticklabels (strings labeling the ticks). The location of the ticks is determined by a Locator object and the ticklabel strings are formatted by a Formatter. The combination of the correct Locator and Formatter gives very fine control over the tick locations and labels.
我的理解是:Axis就是轴线,比如说一个空间直角坐标系中的x轴或y轴。
Artist:Basically everything you can see on the figure is an artist (even the Figure, Axes, and Axis objects). This includes Text objects, Line2D objects, collections objects, Patch objects … (you get the idea). When the figure is rendered, all of the artists are drawn to the canvas. Most Artists are tied to an Axes; such an Artist cannot be shared by multiple Axes, or moved from one to another.
我的理解是:凡是在figure上能看到的所有东西都是Artist。
3.Create new figures
注意,创建一个新figure最简单的方法是用pyplot(一般导入库时会用import…as…取别名plt)
一般在代码开始时会有:
import matplotlib.pylot as plt #给pyplot取了别名plt
接一下给一个简单的创建figure代码:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure() # an empty figure with no Axes
fig, ax = plt.subplots() # a figure with a single Axes
fig, axs = plt.subplots(2,2) # a figure with a 2x2 grid of Axes;2x2的表格
plt.show()
这个代码中创建了3个figure,一个不带轴的,两个带轴的:
4.Types of inputs to plotting functions(绘图函数的输入类型)
在这里,只需要知道所有的绘图函数都适应numpy.array 或者numpy.ma.masked_array作为输入,而pandas或者numpy.matrix等作为输入时绘图函数可能正常工作,也可能不会正常工作,所以建议绘图之前先将这些对象转换为numpy.array。
5.The objected-oriented interface and the pyplot interface(面向对象接口和pyplot接口)
使用Matplotlib绘图时有两种方法:
(1)面向对象风格OO-style:
显式地创建图像和轴,并对它们调方法
例:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 100)
# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots() # Create a figure and an axes.
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()
(2)pyplot-style:
Rely on pyplot to automatically create and manage the figures and axes, and use pyplot functions for plotting.这里采用依靠pyplot函数自动生成管理figures and axes,并且采用pyplot函数绘图
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,2,100)
plt.plot(x,x,label='linear')
plt.plot(x,x**2,label='quadratic')
plt.plot(x,x**3,label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Jiajianghao's figure")
plt.legend()
plt.show()
两幅图的效果一样,但是,官方文档中建议使用一种风格绘图,不要混合使用,一般来说,建议pyplot-style风格进行交互式绘图,非交互式绘图(或者在大型项目中使用),更倾向采用面对对象风格。
Matplotlib’s documentation and examples use both the OO and the pyplot approaches (which are equally powerful), and you should feel free to use either (however, it is preferable pick one of them and stick to it, instead of mixing them). In general, we suggest to restrict pyplot to interactive plotting (e.g., in a Jupyter notebook), and to prefer the OO-style for non-interactive plotting (in functions and scripts that are intended to be reused as part of a larger project).
5.to write specialized functions to do the plotting(写专门的函数用于绘图)
通常情况下,可能进行绘图的数据集不断变化,所以需要写一个函数,通过改变调用的参数来改变生成的图。
import numpy as np
import matplotlib.pyplot as plt
def my_plotter(ax, data1, data2, param_dict):
"""
A helper function to make a graph
Parameters
----------
ax : Axes
The axes to draw to
data1 : array
The x data
data2 : array
The y data
param_dict : dict
Dictionary of kwargs to pass to ax.plot
Returns
-------
out : list
list of artists added
"""
out = ax.plot(data1, data2, **param_dict)
return out
data1, data2, data3, data4 = np.random.randn(4, 100)
fig, ax = plt.subplots(1, 1)
my_plotter(ax, data1, data2, {'marker': 'x'})
plt.show()
6.Backends(后端)
我觉得新手了解这些的必要性不大,需要的储备知识比较多,Usage Guide部分先了解前面的即可。
有兴趣可以去官方文档:Matplotlib 3.3.2 documention