文章目录
1 matplotlib介绍与安装
1.1 matplotlib介绍
matplotlib是一个Python的基础绘图库,它可与Numpy一起使用来代替MATLAB,主要用于在Python中创建静态,动画和交互式可视化图形。
1.2 matplotlib的安装
安装命令:pip install matplotlib
注意:优先使用换源安装,安装完成之后可在pythcharm的终端(terminal)输入命令:pip list
可以查看目前安装的所有包名。
2 matplotlib绘图
2.1 图片与子图
matplotlib所绘制的图位于figure对象中,我们可以通过plt.figure
生成一个新的figure对象
from matplotlib import pyplot as plt
fig = plt.figure()
注意:在IPthon中,执行该代码会出现一个空白的绘图窗口,但在jupter中则没有任何显示。
通过plt.subplot()方法创建一个或多个子图,如下面带有四个子图的matplotlib图片:
plt.subplot() 方法参数:plt.subplot(*arg,**kwargs)
'''
Parameters
----------
*args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
The position of the subplot described by one of
- Three integers (*nrows*, *ncols*, *index*). The subplot will take the
*index* position on a grid with *nrows* rows and *ncols* columns.
*index* starts at 1 in the upper left corner and increases to the
right. *index* can also be a two-tuple specifying the (*first*,
*last*) indices (1-based, and including *last*) of the subplot, e.g.,
``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the
upper 2/3 of the figure.
- A 3-digit integer. The digits are interpreted as if given separately
as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the
same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
if there are no more than 9 subplots.
- A `.SubplotSpec`.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the subplot (`~.axes.Axes`). *str* is the name
of a custom projection, see `~matplotlib.projections`. The default
None results in a 'rectilinear' projection.
polar : bool, default: False
If True, equivalent to projection='polar'.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
axis will have the same limits, ticks, and scale as the axis of the
shared axes.
label : str
A label for the returned axes.
Returns
-------
`.axes.SubplotBase`, or another subclass of `~.axes.Axes`
The axes of the subplot. The returned axes base class depends on
the projection used. It is `~.axes.Axes` if rectilinear projection
is used and `.projections.polar.PolarAxes` if polar projection
is used. The returned axes is then a subplot subclass of the
base class.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for the returned axes
base class; except for the *figure* argument. The keyword arguments
for the rectilinear base class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used.
%(Axes)s
'''
该方法具体用法看代码源文件。
实例:
# 从matplotlib中导入pyplot类
from matplotlib import pyplot as plt
# 创建图片对象
fig = plt.figure()
'''
添加子图到figure对象中
-- nrows 行
-- ncols 列
-- index 取子图得索引,从1开始
'''
# 2 x 2 四个子图,如果index的值大于子图的索引范围会报错。
ax1 = plt.subplot(2,2,1)
ax2 = plt.subplot(2,2,2)
ax3 = plt.subplot(2,2,3)
ax4 = plt.subplot(2,2,4)
# plt.subplot(2,2,5)会报错
# 绘制图形。比如散点图(x,y)构成点
ax1.scatter(range(10),range(10))
ax2.scatter(range(10),range(10))
ax3.scatter(range(10),range(10))
ax4.scatter(range(10),range(10))
# 注意,如果通过plt直接绘制,默认在最后一个子图中绘制图形
plt.scatter(range(10),range(10))
# 展示图形,在pycharm中呈现图形必须使用plt.show()方法
另外,matplotlib可以用另一个便捷方法plt.subplots()创建figure对象并设置了子图,因此有两个返回值:figure和axes。
plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,subplot_kw=None, gridspec_kw=None, **fig_kw)
参数介绍:
-
nrows,ncols:整型,默认为1,控制子图网格的行数/列数。
-
sharex,sharey:布尔型或者{‘none’, ‘all’, ‘row’, ‘col’},默认为False,用来控制所有子图使用相同的x轴刻度/y轴刻度。其中:
-
True or ‘all’: x- or y-axis will be shared among all subplots.
-
False or ‘none’: each subplot x- or y-axis will be independent.
-
‘row’: each subplot row will share an x- or y-axis.
-
‘col’: each subplot column will share an x- or y-axis.
-
-
squeeze:布尔型,默认为True。
(1) 如果为True,则对子图进行压缩。
-
如果只绘制一个子图(即nrows=ncols=1),则生成单个子图作为标量返回。
-
如果绘制 N x 1 或者 1 x M 个子图,则返回Axes对象的一维numpy数组对象。
-
如果绘制 N x M (N>1,M>1)个子图,则返回一个2维数组。
(2)如果为False,则不对子图进行压缩,返回始终包含Axes实例的2D数组(即使是1x1)
-
实例1:
import matplotlib.pyplot as plt
# 创建2*2的子图
fig,axs = plt.subplots(2,2)
# 通过下标(从0开始)访问子图
# 例如:axs[0][0]
# 绘制图形
axs[0,0].scatter(range(10),range(10))
axs[0,1].scatter(range(10),range(10))
axs[1,0].scatter(range(10),range(10))
axs[1,1].scatter(range(10),range(10))
# 展示图形
plt.show()
实例2 :
import numpy as np
from matplotlib import pyplot as plt
# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Simple plot")
如果不需要使用子图时,可以通过matplotlib.pyplot()
方法绘制图形。
2.2 matplotlit绘制图形
matplotlib能够绘制的图形有:折线图、散点图、条形图、直方图、饼图等等。
具体可参考:
https://matplotlib.org/gallery/index.html
2.2.1 折线图
折线图介绍 :以折线的上升或下降来表示统计数量的增减变化的统计图。
特点:能够显示数据的变化趋势,反映事物的变化情况。
折线图绘制:折线图可以通过matplotlib.pyplot.plot()方法来绘制
实例:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [2,3,1,2]
plt.plot(x,y)
plt.show()
注意:x和y必须拥有相同的长度,即 len(x) = len(y)
。
以上实例,x数组对应图形x轴的值,y数组对应图形y轴的值,并且通过plt.plot()
绘制之后, 通过plt.show()
展示图片,释放内存。
plt.plot()函数除了传入制图数据,还可以设置线的颜色等:
- color 设置线的颜色
- linestyle 设置线的样式
- marker 标记样式
例如:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [2,3,1,2]
plt.plot(x,y,color='g',linestyle='--')
plt.show()
plt.plot()参数使用具体可参考:https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot
图形的组成除了x,y轴,还有很多其他组件,图片地址:
https://cdn.nlark.com/yuque/0/2020/png/704747/1585837534064-b69d73b6-ee2b-42e1-ac5e-b81ed8bd8266.png
方法 | 描述 |
---|---|
plt.figure(figsize=None,dpi=None) | 生成新的图片,figsize:图片大小,dpi:透明度 |
plt.savefig(filename) | 保存图片 |
plt.xticks(ticks=None) | 设置x轴刻度的值 |
plt.yticks(ticks=None) | 设置y轴刻度的值 |
plt.xlabel(xlabel) | 设置x轴标签 |
plt.ylabel(ylabel) | 设置y轴标签 |
plt.title() | 设置图形标题 |
plt.grid() | 根据x轴和y轴的数值展示轴网格 |
中文显示问题
当我们需要设置轴标签、标题等,通常会用到中文,但matplotlib默认不显示中文。
解决方法:
- 方法一:全局的方式。注意该方式只支持ttf,不支持ttc。
import matplotlib
font = {
'family':'SimHei',
'weight':'bold',
'size':12
}
matplotlib.rc('font',**font)
- 方法二:通过rcParams参数配置(局部的方式)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一:替换sans-serif字体
plt.rcParams['axes.unicode_minus'] = False # 步骤二:解决坐标轴负数的负号显示问题
- 方法三:读取系统自带的字体
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc',size=14)
x = [1,2,3,4]
y = [3,2,