mpl基础绘图之线形图,点状图
matplotlib是一个建立在numpy上的,开源的python绘图库。绘图是数据可视化必不可少的一环。
matplotlib可以作为matlab绘图的替代。
先来画两个个简单的线形图。
点击查看代码
import matplotlib.pyplot as plt#载入matplotlib的绘图模块pyplot,并且命名为pit。
plt.plot([1,9,6,42,5,6])#这里plot函数接受一个类数组数据,以其默认下标为横坐标,数值为纵坐标绘图(折线图)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()#画板
ax=plt.axes()#坐标轴
x=np.linspace(0,np.pi*10,1000)
ax.plot(x,np.sin(x))#绘图
plt.xlim(-1,20)#x轴取值
plt.ylim(-1,1)#y轴取值
plt.show()#展示
matplotlib为用户提供了两种风格的接口:函数式和对象式。前者类似于matlab编程风格,适用于快速绘制简易图;后者适用于绘制复杂图形。
matlab风格接口绘图的好处在于,它维持绘图的状态(state),持续跟踪当前的图形和坐标轴,所有plt命令都可以应用,因此绘图快而且方便。但绘制多个子图时可能会遇到复杂的问题。
我们主要看面向对象式绘图。
1.简单线形图
- 我们首先要有一块画板(figure),每块画板上要有不同的子图(axes),或者坐标轴。
fig=plt.figure(num=0,figsize=(10,20))#第一个参数为图表编号,第二个为图表大小(绘图后仍可以调整,无关紧要)
ax=plt.axes()
如何理解figure对象呢,首先,它是plt.Figure类的一个实例,它就是一个包含坐标轴,图形,文字的容器,是我们绘画的画板。
axes是plt.Axes类的一个实例,是一个带刻度和标签的矩形,是我们用来绘图的画纸。一块画板当然可以贴好几张画纸。
有了画板fig和画纸ax后,我们就可以用ax.plot()(画笔)绘画了。
请注意,plt.plot()和ax.plot()是两种风格的绘图方式;差异不大,但有一定区别。
plot()函数返回一个列表,列表里面的元素就是我们画出的“线条”对象(<class 'matplotlib.lines.Line2D'>),可供我们直接对其修改属性。我们调用其他的函数比如pie,fill,bar等都是类似的用法。
fig=plt.figure(num=0,figsize=(5,5))
ax=plt.axes()
x=np.linspace(-10,10,1000)
y=np.sin(x)/x
z=x**0.5
ax.plot(x,y,label="$sin(x)/x$",color='blue',linewidth=2,linestyle='--')
ax.plot(x,z,label="$x**0.5$",color='#66ccff',linewidth=1.5,linestyle=':')
'''
color:指定曲线的颜色,颜色可以用英文单词或以#字符开头的6位十六进制数表示,
例如'#ff0000’表示红色。或者使用值在0 到 1范围之内的三个元素的元组来表示,例如
(1.0,0.0,0.0)也表示红色
linewidth: 指定曲线的宽度,可以不是整数,也可以使缩写形式的参数名lw。
label:给曲线指定一个标签,此标签将在图示中显示。如果标签字符串的前后有字符'$',
matplotlib会将其显示为数学公式。
'''
plt.legend()
# legend:显示图示,即图中表示每条曲线的标签(label)和样式的矩形区域。
plt.savefig("the first.png",dpi=240)#保存图片,dpi指定分辨率
plt.show()
2.对线条的调整
颜色和风格:
组合使用:
点击查看代码
fig=plt.figure(num=0,figsize=(5,5))
ax=plt.axes()
x=np.linspace(-10,10,1000)
y=x*np.sin(x**2)
ax.plot(x,y,'-r')
plt.show()
3.对坐标轴的调整
我们可以使用ax.set()方法一次性设置坐标轴所有属性。
点击查看代码
fig=plt.figure(num=0,figsize=(5,5))
ax=plt.axes()
x=np.linspace(-10,10,1000)
y=(x-5)**2-5
ax.plot(x,y,'-r')
ax.set(xlim=(0,10),ylim=(-5,5),xlabel='x',ylabel='y',title='text')
#依次是:x取值范围,y取值范围,x轴标签,y轴标签,图表名称。
plt.show()
函数式绘图的方法转换:
4.axis()方法(注意区分axis与axes)
- axis()接受一个列表,设置x和y的最值。列表元素为[xmin,xmax,ymin,ymax]。
- axis()可以接受其他的参数,比如'tight':自动调整坐标轴取值,收紧空白区域;'equal':令x轴和y轴单位长度相等。
axis(tight)
axis(equal)
2.简单散点图
- plt.plot
之前我们见过这个常用的函数。现在我们用它来画散点图。
函数的主要参数为plot(x,y,[fmt],**kwargs)
第三位参数为格式控制符,例如之前的线条的颜色,格式控制符。与之类似,当我们输入'o','.','x','+','v','^'等不同的格式符(我们称之为marker)时,将会出现不同的散点样式。它们还可以与线条,颜色代码结合使用。
第四位参数意为多组不同的参数,绘制多条线。
fig=plt.figure(num=0,figsize=(5,5))
ax=plt.axes()
x=np.linspace(-10,10,100)
y0=x+1
y1=x-1
y2=np.arange(10)
ax.plot(x,y0,'-^k',label='y0=x+1')#label参数为每条线设置一个标签。
#实线,上三角,黑色
ax.plot(x,y1,'xg',label='y1=x-1')
#散点,×号,绿色
ax.plot(y2,'sr',label='y2={}'.format(y2))
#散点,正方形,红色
ax.set(xlabel='x',ylabel='y',title='text')
ax.legend()#legend函数将每条线的标签与其风格等自动匹配并显示。
plt.show()
2.plt.scatter
plt.scatter与plt.plot相比,具有更高的灵活性,可以单独控制每个散点的属性,如大小颜色等。
先扒一下它的英文文档。
点击查看代码
Help on function scatter in module matplotlib.pyplot:
scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=<deprecated parameter>, edgecolors=None, *, plotnonfinite=False, data=None, **kwargs)
A scatter plot of *y* vs. *x* with varying marker size and/or color.
Parameters
----------
x, y : float or array-like, shape (n, )
The data positions.
s : float or array-like, shape (n, ), optional
The marker size in points**2.
Default is ``rcParams['lines.markersize'] ** 2``.
c : array-like or list of colors or color, optional
The marker colors. Possible values:
- A scalar or sequence of n numbers to be mapped to colors using
*cmap* and *norm*.
- A 2-D array in which the rows are RGB or RGBA.
- A sequence of colors of length n.
- A single color format string.
Note that *c* should not be a single numeric RGB or RGBA sequence
because that is indistinguishable from an array of values to be
colormapped. If you want to specify the same RGB or RGBA value for
all points, use a 2-D array with a single row. Otherwise, value-
matching will have precedence in case of a size matching with *x*
and *y*.
If you wish to specify a single color for all points
prefer the *color* keyword argument.
Defaults to `None`. In that case the marker color is determined
by the value of *color*, *facecolor* or *facecolors*. In case
those are not specified or `None`, the marker color is determined
by the next color of the ``Axes``' current "shape and fill" color
cycle. This cycle defaults to :rc:`axes.prop_cycle`.
marker : `~.markers.MarkerStyle`, default: :rc:`scatter.marker`
The marker style. *marker* can be either an instance of the class
or the text shorthand for a particular marker.
See :mod:`matplotlib.markers` for more information about marker
styles.
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
A `.Colormap` instance or registered colormap name. *cmap* is only
used if *c* is an array of floats.
norm : `~matplotlib.colors.Normalize`, default: None
If *c* is an array of floats, *norm* is used to scale the color
data, *c*, in the range 0 to 1, in order to map into the colormap
*cmap*.
If *None*, use the default `.colors.Normalize`.
vmin, vmax : float, default: None
*vmin* and *vmax* are used in conjunction with the default norm to
map the color array *c* to the colormap *cmap*. If None, the
respective min and max of the color array is used.
It is deprecated to use *vmin*/*vmax* when *norm* is given.
alpha : float, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).
linewidths : float or array-like, default: :rc:`lines.linewidth`
The linewidth of the marker edges. Note: The default *edgecolors*
is 'face'. You may want to change this as well.
edgecolors : {'face', 'none', *None*} or color or sequence of color, default: :rc:`scatter.edgecolors`
The edge color of the marker. Possible values:
- 'face': The edge color will always be the same as the face color.
- 'none': No patch boundary will be drawn.
- A color or sequence of colors.
For non-filled markers, the *edgecolors* kwarg is ignored and
forced to 'face' internally.
plotnonfinite : bool, default: False
Set to plot points with nonfinite *c*, in conjunction with
`~matplotlib.colors.Colormap.set_bad`.
Returns
-------
`~matplotlib.collections.PathCollection`
Other Parameters
----------------
**kwargs : `~matplotlib.collections.Collection` properties
See Also
--------
plot : To plot scatter plots when markers are identical in size and
color.
Notes
-----
* The `.plot` function will be faster for scatterplots where markers
don't vary in size or color.
* Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which
case all masks will be combined and only unmasked points will be
plotted.
* Fundamentally, scatter works with 1-D arrays; *x*, *y*, *s*, and *c*
may be input as N-D arrays, but within scatter they will be
flattened. The exception is *c*, which will be flattened only if its
size matches the size of *x* and *y*.
.. note::
In addition to the above described arguments, this function can take
a *data* keyword argument. If such a *data* argument is given,
the following arguments can also be string ``s``, which is
interpreted as ``data[s]`` (unless this raises an exception):
*x*, *y*, *s*, *linewidths*, *edgecolors*, *c*, *facecolor*, *facecolors*, *color*.
Objects passed as **data** must support item access (``data[s]``) and
membership test (``s in data``).
可以看到也是参数众多。努力试着翻译一下。
参数 | 说明 |
x,y: | 类数组数据,是数据的坐标。 |
s: | 标量或类数组数据,可选参数,默认20,是数据点的大小。 |
c: | 颜色,可选参数,默认为‘b’。不能是单独的RGB数字或RGBA序列。 |
marker: | 数据点的样式。即‘o’,‘x’,‘^’等。 |
cmap: |
字符串或`matplotlib.colors.Colormap`类, 当且仅当c为一个浮点数数组的时候使用。默认为‘image.cmap’(那么这到底是什么意思呢) |
norm: | 如果*c*是一个浮点数数组,则使用*norm*缩放数据亮度,在0到1的范围内,以便映射到colormap。 |
vmin,vmax: | 设置亮度,如果norm实例已使用,该参数无效。 |
alpha: | 实数,设置数据透明度,取值范围0-1。 |
linewidth: | 浮点数或类数组数据,标记点边缘的线宽。默认为None。 |
数据点的颜色以及样式,以下有具体说明:
点击查看代码
x=np.random.rand(50)
y=np.random.rand(50)
plt.scatter(x,y,s=20,c='#66ccff',alpha=0.9,cmap='viridis')
plt.show()