[TOC]
datawhale2021.9组队学习
数据可视化_task01
Matplotlib是一个Python 2D绘图库,能够以多种硬拷贝格式和跨平台的交互式环境生成出版物质量的图形,用来绘制各种静态,动态,交互式的图表。
Matplotlib可用于Python脚本,Python和IPython Shell、Jupyter notebook,Web应用程序服务器和各种图形用户界面工具包等。
Matplotlib是Python数据可视化库中的泰斗,它已经成为python中公认的数据可视化工具,我们所熟知的pandas和seaborn的绘图接口其实也是基于matplotlib所作的高级封装。
为了对matplotlib有更好的理解,让我们从一些最基本的概念开始认识它,再逐渐过渡到一些高级技巧中。
1. 绘图例子
Matplotlib的图像是画在figure(如windows,jupyter窗体)上的,每一个figure又包含了一个或多个axes(一个可以指定坐标系的子区域)。最简单的创建figure以及axes的方式是通过pyplot.subplots
命令,创建axes以后,可以使用Axes.plot
绘制最简易的折线图。
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots() # 创建一个包含一个axes的figure
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]); # 绘制图像
复制代码
注意:
在jupyter notebook中使用matplotlib时会发现,代码运行后自动打印出类似[<matplotlib.lines.Line2D at 0x248c0f10c70>]
这样一段话,这是因为matplotlib的绘图代码默认打印出最后一个对象。如果不想显示这句话,有以下三种方法,在本章节的代码示例中你能找到这三种方法的使用。
- 在代码块最后加一个分号
;
- 在代码块最后加一句plt.show()
- 在绘图时将绘图对象显式赋值给一个变量,如将plt.plot([1, 2, 3, 4]) 改成line =plt.plot([1, 2, 3, 4])
1.1 plot()函数
Signature: plt.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
复制代码
- x, y:点或线的节点,x 为 x 轴数据,y 为 y 轴数据,数据可以列表或数组。
- fmt:可选,定义基本格式(如颜色、标记和线条样式)。
**kwargs
:可选,用在二维平面图上,设置指定属性,如标签,线的宽度等。
plot(x, y) # plot x and y using default line style and color
plot(x, y, 'bo') # plot x and y using blue circle markers
plot(y) # plot y using x as index array 0..N-1
plot(y, 'r+') # ditto, but with red plusses
复制代码
可以使用关键字声明或者格式字符串来定义线条和标记点的样式,两种形式可以混用,但在存在冲突时,关键字声明会覆盖格式字符串.
plot(x, y, 'go--', linewidth=2, markersize=12)
plot(x, y, color='green', marker='o', linestyle='dashed',linewidth=2, markersize=12)
复制代码
import matplotlib.pyplot as plt
import numpy as np
fig,ax = plt.subplots()
ax.plot([1,2,3,4],[4,1,3,2],'or--',linewidth=2,markersize=14)
plt.show()
复制代码
1.1.1 绘制带标记的数据
有一种方便的方法来绘制带有标记数据的对象(即可以通过索引obj['y']
访问的数据)。 而不是给予x 和 y 中的数据,您可以提供 data 中的对象参数并只给出 x 和 y 的标签:
plot('xlabel', 'ylabel', data=obj)
复制代码
支持所有可索引对象。 这可以例如 是一个dict
,一个
pandas.DataFrame
或结构化的 numpy 数组。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2*np.pi, 0.02)
y = np.sin(x)
fig,ax = plt.subplots()
plotdict = {'dx':x,'dy':y}
ax.plot('dx','dy',data=plotdict)
plt.show()
复制代码
此时提示plot()
的第二个参数’dy’可能存在歧义,可能是一个fmt
参数,应该添加一个空的fmt
参数.
ax.plot('dx','dy',''data=plotdict)
1.1.2 绘制多组数据
有多种方法可以绘制多组数据。
- 最直接的方法就是多次调用
plot
。
plot(x1, y1, 'bo')
plot(x2, y2, 'go')
复制代码
- 或者,如果您的数据已经是二维数组,则可以传递它直接到 x, y。 每一列将会绘制成单独的数据集。
示例:一个数组“a”,其中第一列代表x值和其他列是 y 列::
plot(a[0], a[1:])
复制代码
此处存疑,应该取列数据.plt.plot(plotarr[:,0],plotarr[:,1:])
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2,100)
y1 = x
y2 = x**2
y3 = x**3
plotarr = np.array([x,y1,y2,y3]).transpose()
plt.plot(plotarr[:,0],plotarr[:,1:])
plt.show()
复制代码
- 第三种方式是指定多组*[x]、y、[fmt]*:
plot(x1, y1, 'g^', x2, y2, 'g-')
复制代码
在这种情况下,任何额外的关键字参数适用于所有数据集。 此外,此语法不能与 data范参数。
默认情况下,每行都被分配了一个由指定的不同样式’style cycle’。 如果您希望与这些默认值有明显的偏差,fmt 和 line 属性参数则是必要的。或者,您也可以使用:rc:axes.prop_cycle
。
1.1.3 参数字典
1.1.3.1 **kwargs
**kwargs
.Line2D
属性,可选.用于指定属性诸如线条标签(用于自动图例)、线宽、抗锯齿、标记颜色。
plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
复制代码
如果你用一个 plot 调用创建多个线条,kwargs适用于所有这些线条。
Properties:
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha: float or None
animated: bool
antialiased or aa: bool
clip_box: .Bbox
clip_on: bool
clip_path: Patch or (Path, Transform) or None
color or c: color
contains: unknown
dash_capstyle: {‘butt’, ’round’, ‘projecting’}
dash_joinstyle: {‘miter’, ’round’, ‘bevel’}
dashes: sequence of floats (on/off ink in points) or (None, None)
data: (2, N) array or two 1D arrays
drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’
figure: .Figure
fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’}
gid: str
in_layout: bool
label: object
linestyle or ls: {‘-‘, ‘–‘, ‘-.’, ‘:’, ”, (offset, on-off-seq), …}
linewidth or lw: float
marker: marker style string, ~.path.Path
or ~.markers.MarkerStyle
markeredgecolor or mec: color
markeredgewidth or mew: float
markerfacecolor or mfc: color
markerfacecoloralt or mfcalt: color
markersize or ms: float
markevery: None or int or (int, int) or slice or List[int] or float or (float, float) or List[bool]
path_effects: .AbstractPathEffect
picker: unknown
pickradius: float
rasterized: bool or None
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
solid_capstyle: {‘butt’, ’round’, ‘projecting’}
solid_joinstyle: {‘miter’, ’round’, ‘bevel’}
transform: matplotlib.transforms.Transform
url: str
visible: bool
xdata: 1D array
ydata: 1D array
zorder: float
1.1.3.2 fmt
格式字符串由颜色、标记和线条的一部分组成:
fmt = [marker][line][color]
Each of them is optional. If not provided, the value from the style
cycle is used. Exception: If line
is given, but no marker
,
the data will be a line without markers.
它们中的每一个都是可选的。 如果未提供,则来自style cycle。 例外:如果给出了“line”,但没有“marker”,数据将是一条没有标记的线。
其他组合如[color][marker][line]
也是支持的,但请注意,它们的解析可能不明确。
Markers
============= ===============================
character description
============= ===============================
'.'
point marker
','
pixel marker
'o'
circle marker
'v'
triangle_down marker
'^'
triangle_up marker
'<'
triangle_left marker
'>'
triangle_right marker
'1'
tri_down marker
'2'
tri_up marker
'3'
tri_left marker
'4'
tri_right marker
's'
square marker
'p'
pentagon marker
'*'
star marker
'h'
hexagon1 marker
'H'
hexagon2 marker
'+'
plus marker
'x'
x marker
'D'
diamond marker
'd'
thin_diamond marker
'|'
vline marker
'_'
hline marker
============= ===============================
Line Styles
============= ===============================
character description
============= ===============================
'-'
solid line style
'--'
dashed line style
'-.'
dash-dot line style
':'
dotted line style
============= ===============================
Example format strings::
'b' # blue markers with default shape
'or' # red circles
'-g' # green solid line
'--' # dashed line with default color
'^k:' # black triangle_up markers connected by a dotted line
复制代码
Colors
The supported color abbreviations are the single letter codes
============= ===============================
character color
============= ===============================
'b'
blue
'g'
green
'r'
red
'c'
cyan
'm'
magenta
'y'
yellow
'k'
black
'w'
white
============= ===============================
and the 'CN'
colors that index into the default property cycle.
如果颜色是格式字符串的唯一部分,您可以另外使用任何matplotlib.colors
规范,例如 全名('green'
) 或十六进制字符串 ('#008000'
)。
2. figure的组成
现在我们来深入看一下figure的组成。通过一张figure解剖图,我们可以看到一个完整的matplotlib图像通常会包括以下四个层级,这些层级也被称为容器(container),下一节会详细介绍。在matplotlib的世界中,我们将通过各种命令方法来操纵图像中的每一个部分,从而达到数据可视化的最终效果,一副完整的图像实际上是各类子元素的集合。
-
Figure
:顶层级,用来容纳所有绘图元素 -
Axes
:matplotlib宇宙的核心,容纳了大量元素用来构造一幅幅子图,一个figure可以由一个或多个子图组成 -
Axis
:axes的下属层级,用于处理所有和坐标轴,网格有关的元素 -
Tick
:axis的下属层级,用来处理所有和刻度有关的元素
3. 两种绘图接口
matplotlib提供了两种最常用的绘图接口
- 显式创建figure和axes,在上面调用绘图方法,也被称为OO模式(object-oriented style)
x = np.linspace(0, 2, 100)
fig, ax = plt.subplots()
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_title("Simple Plot")
ax.legend()
plt.show()
复制代码
2. 依赖pyplot自动创建figure和axes,并绘图
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("Simple Plot")
plt.legend()
plt.show()
复制代码