为了处理数据和绘图,我们首先导入第三方包Numpy和快速绘图模块pyplot。
我们可以通过在命令行提示符cmd(对于Windows系统)或者终端Terminal(对于Mac系统)使用下述命令安装Matplotlib:
pip install matplotlib
如果已经是使用Anaconda作为编程集成环境,那电脑中已经装好该库了,无需再次安装。
一般我们在使用时都是导入该库的pyplot模块,将其简写为plt
import matplotlib.pyplot as plt
在绘图时我们往往也会结合Numpy库一起使用。
Matplotlib 可以绘制丰富的科学图形和统计图形,如折线图、散点图、直方图等,下面具体介绍这些图形的绘制方法。 首先将绘图库等进行导入,然后准备相应的绘图数据。
import numpy as np # 引入Numpy库
import matplotlib.pyplot as plt # 引入pyplot模块
%matplotlib inline # 设置matplotlib的图像直接在jupyter notebook行间进行显示
plot()¶plot函数可以展现变量的变化趋势
plt.plot(x,y,ls='-',lw=2,label='plot figure')x:x轴上的数值y: y轴上的数值ls: linestyle,折线的线条风格lw: linewidth,折线的线条宽度label: 标记图形内容的标签文本
例如x = np.linspace(0,2,100) # 生成从0.05 到 10 等分的1000个数据
y = x**2 # 二次函数
y2 = x**0.5 # 根式
plt.plot(x,y,'c',ls='-',lw=3,label='Square') # 线性为虚线--,线宽为6,标签为'My first line'
plt.plot(x,y2,'b',ls='-',lw=3,label='Root')
plt.legend() # 显示图例,不加这一句则不显示图例
plt.xlabel('X') # 设置横坐标名称
plt.ylabel('Y') # 设置纵坐标名称
plt.title('Plot') # 设置标题
plt.savefig('images/mat0101.png') # 将图片保存
scatter()¶散点图可以用来寻找变量之间的关系
plt.scatter(x,y,c='b',label = 'scatter figure')x: $x$轴上的数值y: $y$轴上的数值c: 散点图中的标记颜色label: 标记图形内容的标签文本s: 标记的大小cmap: 标记的颜色映射表x = np.linspace(0.05,10,100) # 生成从0.05 到 10 等分的100个数据
y = np.random.rand(100)# 生成100个正态分布的随机数
y1 = np.random.rand(100) # 生成100个正态分布的随机数
plt.scatter(x,y,c= 'b',label='Scatter 1') # 绘制第一组数据
plt.scatter(x,y1,c= 'r',label='Scatter 2') # 绘制第二组数据
plt.legend() # 增加图例
plt.grid() # 绘制网格线
plt.title('Scatter') # 设置标题
plt.savefig('images/mat0102.png') # 将图片保存
bar()¶`bar()'函数可以在x轴上绘制定性数据的分布特征。
plt.bar(x,y)x: 标示在x轴上的定性数据的分布特征y: 每种定性数据类别的数量x = [1,2,3,4,5,6,7,8]
y = [3,1,4,5,8,9,7,2]
plt.bar(x,y,align='center',color='k',tick_label =list('ABCDEFGH')) # 设置横纵坐标数据、柱状图放置位置,颜色
plt.xlabel('X') # 设置横坐标标题
plt.ylabel('Y') # 设置纵坐标标题
plt.grid(axis = 'y') # 只绘制平行于x轴的格线
plt.title('Bar') # 设置标题
plt.savefig('images/mat0103.png') # 将图片保存
hist()¶hist函数可以x轴上绘制定量数据的分布特征。
plt.hist(x)x: 在$x$轴上绘制的数据bins: 在$x$轴上分割的直方个数color: 直方颜色rwidth: 直方宽度占比alpha: 透明度x = np.random.randint(0,10,100) # 生成0-10共100个随机数
bins = range(0,10,1) # 设置bins数据,
plt.hist(x,
bins = bins,
color = 'c',
rwidth=0.8,
alpha=0.5)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Histogram') # 设置标题
plt.savefig('images/mat0104.png') # 将图片保存
pie()¶饼图pie可以绘制定性数据的不同类型的百分比
plt.pie(x)x: 定性数据的不同类型的百分比explode: 显示要突出的部分与其他部分的距离label: 各个类型的标签autopct: 显示百分比并设定小数点位数colors: 设置各部分的颜色nums = [0.05,0.45,0.15,0.35]
kinds = ['A','B','C','D']
colors = ["C1","C2","C3","C4"]
plt.figure(figsize=(8,8)) # 设置图片大小
plt.pie(nums, # 各个类型的数量
explode=[0.05,0,0,0], # 显示要突出的部分与其他部分的距离
labels=kinds, # 各个类型的标签
autopct="%3.1f%%", # 显示百分比并设定小数点位数
colors=colors) # 显示颜色
plt.title('Pie') # 设置标题
plt.savefig('images/mat0105.png') # 将图片保存
boxplot()¶boxplot可以用来绘制箱线图
plt.boxplot(x)x: 箱线图的输入数据x = np.random.normal(0,1,1000) # 生成正态分布数据
plt.boxplot(x) # 绘制箱线图
plt.xlabel('A') # 设置横坐标
plt.ylabel('Y') # 设置纵坐标标签
plt.grid(linestyle = '--',alpha = 0.3) # 设置网格线
plt.title('Boxplot') # 设置标题
plt.savefig('images/mat0106.png') # 将图片保存
import numpy as np # 引入Numpy库
import matplotlib.pyplot as plt # 引入pyplot模块
%matplotlib inline
x = np.linspace(0,2,100) # 生成从0.05 到 10 等分的1000个数据
y = x**2 # 二次函数
y2 = x**0.5 # 根式
plt.plot(x,y,'c',ls='-',lw=3,label='Square') # 线性为虚线--,线宽为6,标签为'My first line'
plt.plot(x,y2,'b',ls='-',lw=3,label='Root')
plt.legend() # 显示图例,不加这一句则不显示图例
plt.xlabel('X') # 设置横坐标名称
plt.ylabel('Y') # 设置纵坐标名称
plt.title('Plot') # 设置标题
plt.savefig('images/mat0101.png') # 将图片保存
import matplotlib
a = np.random.randn(20)
b = np.random.randn(20)
plt.scatter(a,b,
s = 500*a,
c = np.random.randn(20),
cmap=matplotlib.cm.RdYlBu,
marker='o')
plt.grid() # 绘制网格线
plt.title('Scatter') # 设置标题
plt.savefig('images/mat0102.png') # 将图片保存
D:\software_install\anaconda\lib\site-packages\matplotlib\collections.py:922: RuntimeWarning: invalid value encountered in sqrt scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
x = [1,2,3,4,5,6,7,8]
y = [3,1,4,5,8,9,7,2]
plt.bar(x,y,align='center',color='k',tick_label =list('ABCDEFGH')) # 设置横纵坐标数据、柱状图放置位置,颜色
plt.xlabel('X') # 设置横坐标标题
plt.ylabel('Y') # 设置纵坐标标题
plt.grid(axis = 'y') # 只绘制平行于x轴的格线
plt.title('Bar') # 设置标题
plt.savefig('images/mat0103.png') # 将图片保存
help(plt.bar)
Help on function bar in module matplotlib.pyplot:
bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
Make a bar plot.
The bars are positioned at *x* with the given *align*\ment. Their
dimensions are given by *height* and *width*. The vertical baseline
is *bottom* (default 0).
Many parameters can take either a single value applying to all bars
or a sequence of values, one for each bar.
Parameters
----------
x : float or array-like
The x coordinates of the bars. See also *align* for the
alignment of the bars to the coordinates.
height : float or array-like
The height(s) of the bars.
width : float or array-like, default: 0.8
The width(s) of the bars.
bottom : float or array-like, default: 0
The y coordinate(s) of the bars bases.
align : {'center', 'edge'}, default: 'center'
Alignment of the bars to the *x* coordinates:
- 'center': Center the base on the *x* positions.
- 'edge': Align the left edges of the bars with the *x* positions.
To align the bars on the right edge pass a negative *width* and
``align='edge'``.
Returns
-------
`.BarContainer`
Container with all the bars and optionally errorbars.
Other Parameters
----------------
color : color or list of color, optional
The colors of the bar faces.
edgecolor : color or list of color, optional
The colors of the bar edges.
linewidth : float or array-like, optional
Width of the bar edge(s). If 0, don't draw edges.
tick_label : str or list of str, optional
The tick labels of the bars.
Default: None (Use default numeric labels.)
xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional
If not *None*, add horizontal / vertical errorbars to the bar tips.
The values are +/- sizes relative to the data:
- scalar: symmetric +/- values for all bars
- shape(N,): symmetric +/- values for each bar
- shape(2, N): Separate - and + values for each bar. First row
contains the lower errors, the second row contains the upper
errors.
- *None*: No errorbar. (Default)
See :doc:`/gallery/statistics/errorbar_features`
for an example on the usage of ``xerr`` and ``yerr``.
ecolor : color or list of color, default: 'black'
The line color of the errorbars.
capsize : float, default: :rc:`errorbar.capsize`
The length of the error bar caps in points.
error_kw : dict, optional
Dictionary of kwargs to be passed to the `~.Axes.errorbar`
method. Values of *ecolor* or *capsize* defined here take
precedence over the independent kwargs.
log : bool, default: False
If *True*, set the y-axis to be log scale.
**kwargs : `.Rectangle` properties
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: unknown
capstyle: {'butt', 'round', 'projecting'}
clip_box: `.Bbox`
clip_on: bool
clip_path: Patch or (Path, Transform) or None
color: color
contains: unknown
edgecolor or ec: color or None or 'auto'
facecolor or fc: color or None
figure: `.Figure`
fill: bool
gid: str
hatch: {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout: bool
joinstyle: {'miter', 'round', 'bevel'}
label: object
linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw: float or None
path_effects: `.AbstractPathEffect`
picker: None or bool or callable
rasterized: bool or None
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
transform: `.Transform`
url: str
visible: bool
zorder: float
See Also
--------
barh: Plot a horizontal bar plot.
Notes
-----
Stacked bars can be achieved by passing individual *bottom* values per
bar. See :doc:`/gallery/lines_bars_and_markers/bar_stacked`.
.. note::
In addition to the above described arguments, this function can take
a *data* keyword argument. If such a *data* argument is given,
every other argument can also be string ``s``, which is
interpreted as ``data[s]`` (unless this raises an exception).
Objects passed as **data** must support item access (``data[s]``) and
membership test (``s in data``).
x = np.random.randint(0,10,100) # 生成0-10共100个随机数
bins = range(0,10,1) # 设置bins数据,
plt.hist(x,
bins = bins,
color = 'c',
rwidth=0.8,
alpha=0.5)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Histogram') # 设置标题
plt.savefig('images/mat0104.png') # 将图片保存
nums = [0.05,0.45,0.15,0.35]
kinds = ['A','B','C','D']
colors = ["C1","C2","C3","C4"]
plt.figure(figsize=(8,8)) # 设置图片大小
plt.pie(nums, # 各个类型的数量
explode=[0.05,0,0,0], # 显示要突出的部分与其他部分的距离
labels=kinds, # 各个类型的标签
autopct="%3.1f%%", # 显示百分比并设定小数点位数
colors=colors) # 显示颜色
plt.title('Pie') # 设置标题
plt.savefig('images/mat0105.png') # 将图片保存
x = np.random.normal(0,1,1000) # 生成正态分布数据
plt.boxplot(x) # 绘制箱线图
plt.xlabel('A') # 设置横坐标
plt.ylabel('Y') # 设置纵坐标标签
plt.grid(linestyle = '--',alpha = 0.3) # 设置网格线
plt.title('Boxplot') # 设置标题
plt.savefig('images/mat0106.png') # 将图片保存