---
title: Python数据可视化：Matplotlib常用操作(基础篇)
summary: Matplotlib介绍 Matplotlib是一个Python 2D绘图库，它以多种硬拷贝格式和跨平台的交互式环境生成出版物质量的图形。 Matplotlib可用于Python脚本，Python和IPython Shell、Jupyter…
date: 2023-08-21T17:35:57.000Z
category: python
tags:
  - python
  - data-analysis
  - data-visualization
cover: https://img.cent1pedee.top/img/python-matplotlib.jpg
---

**Matplotlib介绍**

- Matplotlib是一个Python 2D绘图库，它以多种硬拷贝格式和跨平台的交互式环境生成出版物质量的图形。 Matplotlib可用于Python脚本，Python和[IPython](https://ipython.org/) Shell、[Jupyter](http://jupyter.org/)笔记本，Web应用程序服务器和四个图形用户界面工具包。
- Matplotlib 尝试使容易的事情变得更容易，使困难的事情变得可能。 您只需几行代码就可以生成图表、直方图、功率谱、条形图、误差图、散点图等。 更多的示例，请参见[基础绘图例子](https://matplotlib.org.cn/tutorials/introductory/sample_plots.html)和[示例陈列馆](https://matplotlib.org.cn/gallery/)。
- 为了简单绘图，该 **pyplot** 模块提供了类似于MATLAB的界面，尤其是与IPython结合使用时。 对于高级用户，您可以通过面向对象的界面或MATLAB用户熟悉的一组功能来完全控制线型，字体属性，轴属性等。

**安装**

访问[Matplotlib安装说明](https://matplotlib.org.cn/users/installing.html)。

关于Python Matplotlib的用法总结请参考博文：https://matplotlib.org.cn/intro/

下面是部分例题以便更好的理解**Matplotlib**

***

## 简单绘图题（Matplotlib）

### 绘制以下两个函数的图像

### 1、设定一个你喜欢的绘图风格；


```python
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("seaborn-whitegrid")
```


### 2、绘制折线图：

* 根据下面的X和Y按要求绘图
* x = np.linspace(0, 2*np.pi, 100)
* 函数1：y1 = 1 / 1 + np.exp(-x)
* 函数2：y2 = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))


* 对线条的颜色、形状、粗细进行设置；
* 对数据点的形状、大小和颜色进行设置；
* 调整坐标轴的范围，调整坐标轴刻度的大小；
* 增加x轴、y轴的标签以及图像标题；
* 增加图例、添加箭头和文字；
* 将最终绘制好的图像保存到本地文件夹。


```python
# 默认原始图形

x = np.linspace(0, 2*np.pi, 100)
y1 = 1 / 1 + np.exp(-x)
y2 = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))

plt.plot(x, y1)
plt.plot(x, y2)
```





    [<matplotlib.lines.Line2D at 0x249eac5e280>]




    
![png](https://imgbed.kouseki.cn/file/d9e1dad1e27b58bdf84e6.png)
    



```python
#(1) 对线条的颜色、形状、粗细进行设置；
plt.plot(x, y1,'r--',linewidth=10)
plt.plot(x, y2,'g-',linewidth=5)
```





    [<matplotlib.lines.Line2D at 0x249eacbaee0>]




    
![png](https://imgbed.kouseki.cn/file/a605e7615a48eaa1fcaf5.png)
    



```python
#(2)对数据点的形状、大小和颜色进行设置；
plt.plot(x, y1,'r*',markersize=5)
plt.plot(x, y2,'go',markersize=5)
```





    [<matplotlib.lines.Line2D at 0x249eaf7ebe0>]




    
![png](https://imgbed.kouseki.cn/file/3895d2a264c346a5c0921.png)
    



```python
#对线条的颜色、形状、粗细进行设置；
#对数据点的形状、大小和颜色进行设置；

plt.plot(x, y1,'r*--',markersize=5,linewidth=10)
plt.plot(x, y2,'go-',markersize=5,linewidth=5)
```





    [<matplotlib.lines.Line2D at 0x249ead2d130>]




    
![png](https://imgbed.kouseki.cn/file/023320c0a3fdc2fe4ab03.png)
    



```python
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, 1 / 1 + np.exp(-x))
plt.plot(x, (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)), linewidth=10, c='g')
```





    [<matplotlib.lines.Line2D at 0x24a8b56ba60>]




    
![png](https://imgbed.kouseki.cn/file/7668a0cc5c8fb17b0a591.png)
    



```python
plt.plot(x, 1 / 1 + np.exp(-x), 'r+:', markersize=5)
plt.plot(x, (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)), 'g*--', markersize=5)
```





    [<matplotlib.lines.Line2D at 0x24a8b66c160>]




    
![png](https://imgbed.kouseki.cn/file/5d4a5db02a86073aed590.png)
    



```python
#调整坐标轴的范围
plt.plot(x, 1 / 1 + np.exp(-x))
plt.plot(x, (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)))
plt.xlim(-2, 10)
plt.ylim(0, 3)
```





    (0.0, 3.0)




    
![png](https://imgbed.kouseki.cn/file/7a9b30d66ea9b2679d956.png)
    



```python
#调整坐标轴刻度的大小；
plt.plot(x, 1 / 1 + np.exp(-x))
plt.plot(x, (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)))
plt.xticks(np.arange(0, 7, step=0.5), fontsize=10)
plt.yticks(np.arange(0, 2, step=0.5), fontsize=10)
```





    ([<matplotlib.axis.YTick at 0x24a8b70d7c0>,
      <matplotlib.axis.YTick at 0x24a8b70d3a0>,
      <matplotlib.axis.YTick at 0x24a8b709220>,
      <matplotlib.axis.YTick at 0x24a8b746fd0>],
     [Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, '')])




    
![png](https://imgbed.kouseki.cn/file/9099544b6105d61dd1ca0.png)
    



```python
plt.plot(x, 1 / 1 + np.exp(-x))
plt.plot(x, (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)))
plt.title("1 / 1 + e^x", fontsize=20)
plt.xlabel("(e^x - e^(-x))/ (e^x + e^(-x))", fontsize=20)
plt.ylabel("y", fontsize=20)
```





    Text(0, 0.5, 'y')




    
![png](https://imgbed.kouseki.cn/file/f0768a4cb110c07620507.png)
    



```python
plt.plot(x, 1 / 1 + np.exp(-x), label="1 / 1 + e^x")
plt.plot(x, (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)), label="(e^x - e^(-x))/ (e^x + e^(-x))")
plt.title("1 / 1 + e^x", fontsize=20)
plt.xlabel("(e^x - e^(-x))/ (e^x + e^(-x))", fontsize=20)
plt.ylabel("y", fontsize=20)
plt.legend(loc="best", frameon=True, fontsize=15)
plt.annotate('zero point', xy=(5, 1), xytext=(3, 0.75), fontsize=15,
             arrowprops=dict(arrowstyle='->', facecolor='black'),
             )
plt.savefig('my_figure.png')
```



    
![png](https://imgbed.kouseki.cn/file/33a4f8a15f0d2fdbe0527.png)
    


### 3、绘制散点图：


```python
plt.scatter(x, 1 / 1 + np.exp(-x), c=(1 / 1 + np.exp(-x)), s=100 * np.random.rand(100), cmap="viridis", alpha=0.2)
plt.scatter(x, (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)), c=((np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))), s= 50 * np.random.rand(100), cmap="viridis", alpha=0.7)
plt.colorbar()
```





    <matplotlib.colorbar.Colorbar at 0x24a8b8c7cd0>




    
![png](https://imgbed.kouseki.cn/file/d862bbd8efcf48a344eaa.png)
    


* 按y值的大小进行颜色配置，选择一个你喜欢的颜色映射；
* 生成一个随机序列，点的大小依赖于对应位置的随机序列的值；
* 设置不同的透明度。

### 4、绘制柱形图：

* 利用函数1，生成一系列x, y，并绘制柱形图；
* 利用函数2，生成一系列x, y，并绘制横向柱形图；
* 利用函数1、2，生成一系列x, y，并绘制累加柱形图和并列柱形图；


```python
x = np.linspace(1, 10, 5)
y = 1 / 1 + np.exp(-x)
plt.bar(x, y, align='center', width=0.5)
plt.tick_params(axis='both', labelsize=13)
plt.xticks(np.arange(0, 11, step=0.5))
```





    ([<matplotlib.axis.XTick at 0x24a8b92d1c0>,
      <matplotlib.axis.XTick at 0x24a8b92d190>,
      <matplotlib.axis.XTick at 0x24a8b926d30>,
      <matplotlib.axis.XTick at 0x24a8b9587c0>,
      <matplotlib.axis.XTick at 0x24a8b958cd0>,
      <matplotlib.axis.XTick at 0x24a8b965220>,
      <matplotlib.axis.XTick at 0x24a8b965730>,
      <matplotlib.axis.XTick at 0x24a8b965c40>,
      <matplotlib.axis.XTick at 0x24a8b96b190>,
      <matplotlib.axis.XTick at 0x24a8b965970>,
      <matplotlib.axis.XTick at 0x24a8b958a00>,
      <matplotlib.axis.XTick at 0x24a8b96b6a0>,
      <matplotlib.axis.XTick at 0x24a8b96bbb0>,
      <matplotlib.axis.XTick at 0x24a8b972100>,
      <matplotlib.axis.XTick at 0x24a8b972610>,
      <matplotlib.axis.XTick at 0x24a8b972b20>,
      <matplotlib.axis.XTick at 0x24a8b975070>,
      <matplotlib.axis.XTick at 0x24a8b975580>,
      <matplotlib.axis.XTick at 0x24a8b9726a0>,
      <matplotlib.axis.XTick at 0x24a8b96b730>,
      <matplotlib.axis.XTick at 0x24a8b975880>,
      <matplotlib.axis.XTick at 0x24a8b975c40>],
     [Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, ''),
      Text(0, 0, '')])




    
![png](https://imgbed.kouseki.cn/file/9ed19363c45be86b48c15.png)
    



```python
x = np.linspace(1, 10, 5)
y = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))
plt.barh(x, y, align='center')
```





    <BarContainer object of 5 artists>




    
![png](https://imgbed.kouseki.cn/file/aea51d082aa8615b2f6be.png)
    



```python
x = np.linspace(1, 10, 5)
y1 = 1 / 1 + np.exp(-x)
y2 = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))
plt.bar(x, y1, align='center', width=0.5)
plt.bar(x + 0.5, y2, align='center', width=0.5)
```





    <BarContainer object of 5 artists>




    
![png](https://imgbed.kouseki.cn/file/2cfd38dbe408cd630c309.png)
    



```python
x = np.linspace(1, 10, 5)
y1 = 1 / 1 + np.exp(-x)
y2 = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))
plt.bar(x, y1, align='center', width=0.5)
plt.bar(x, y2, bottom=y1, align='center', width=0.5)
```





    <BarContainer object of 5 artists>




    
![png](https://imgbed.kouseki.cn/file/ed17559fe66ffec61829d.png)
    


### 5、多子图：

* 在函数1、2的基础上，增加正弦函数和余弦函数，绘制2*2的多子图。


```python
x = np.linspace(0, 4 * np.pi, 10000)
y1 = 1 / 1 + np.exp(-x)
y2 = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))
y3 = np.sin(x)
y4 = np.cos(x)

plt.subplot(321)
plt.plot(x, y1)

plt.subplot(322)
plt.plot(x, y2)

plt.subplot(323)
plt.plot(x, y3)

plt.subplot(324)
plt.plot(x, y4)
```





    [<matplotlib.lines.Line2D at 0x24a8b7c7820>]




    
![png](https://imgbed.kouseki.cn/file/d6a76a1ed8f9fad581ce0.png)
    


### 6、直方图：

* 构造一个标准正态分布，绘制频次直方图、概率密度直方图、累计概率直方图。


```python
mu, sigma = 85, 10
x = mu + sigma * np.random.randn(10000)
plt.hist(x, bins=50)
```





    (array([  3.,   2.,   1.,   7.,   3.,   8.,   8.,  25.,  28.,  36.,  72.,
             70., 122., 118., 165., 219., 300., 311., 397., 430., 516., 580.,
            595., 627., 612., 661., 568., 535., 500., 455., 434., 371., 278.,
            215., 196., 139., 101.,  86.,  58.,  48.,  41.,  18.,  14.,  11.,
              8.,   6.,   1.,   0.,   0.,   1.]),
     array([ 46.8047152 ,  48.35161112,  49.89850705,  51.44540298,
             52.9922989 ,  54.53919483,  56.08609076,  57.63298669,
             59.17988261,  60.72677854,  62.27367447,  63.82057039,
             65.36746632,  66.91436225,  68.46125818,  70.0081541 ,
             71.55505003,  73.10194596,  74.64884188,  76.19573781,
             77.74263374,  79.28952967,  80.83642559,  82.38332152,
             83.93021745,  85.47711337,  87.0240093 ,  88.57090523,
             90.11780116,  91.66469708,  93.21159301,  94.75848894,
             96.30538486,  97.85228079,  99.39917672, 100.94607265,
            102.49296857, 104.0398645 , 105.58676043, 107.13365635,
            108.68055228, 110.22744821, 111.77434414, 113.32124006,
            114.86813599, 116.41503192, 117.96192784, 119.50882377,
            121.0557197 , 122.60261563, 124.14951155]),
     <BarContainer object of 50 artists>)




    
![png](https://imgbed.kouseki.cn/file/8a4d42cd166a08cf0c34f.png)
    



```python
mu, sigma = 85, 10
x = mu + sigma * np.random.randn(10000)
plt.hist(x, bins=50, density=True, color='r')
plt.text(60, .035, r'$\mu=100,\ \sigma=15$')
```





    Text(60, 0.035, '$\\mu=100,\\ \\sigma=15$')




    
![png](https://imgbed.kouseki.cn/file/245a004976a2de2dd5307.png)
    



```python
mu, sigma = 85, 10
x = mu + sigma * np.random.randn(10000)
plt.hist(x, 50, density=True, cumulative=True, color="g")
plt.text(60, .035, r'$\mu=100,\ \sigma=15$')
```





    Text(60, 0.035, '$\\mu=100,\\ \\sigma=15$')




    
![png](https://imgbed.kouseki.cn/file/76088d82f5ce6d11b6749.png)
    


### 7、误差图：

* 利用函数 1，生成一系列x, y，随机生成一系列误差dy，绘制误差图。


```python
x = np.linspace(0, 4 * np.pi, 25)
y = 1 / 1 + np.exp(-x)
dy = np.random.rand(25)

plt.errorbar(x, y, dy, fmt='+b')
```





    <ErrorbarContainer object of 3 artists>




    
![png](https://imgbed.kouseki.cn/file/be2ad3789c09ce2d36a0c.png)
    


## 简单绘图题（其他）

### 1、面向对象绘图

* 利用函数 1 和函数2，绘制一个画中画。


```python
x = np.linspace(0, 4 * np.pi, 10000)
y1 = 1 / 1 + np.exp(-x)
y2 = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))

fig = plt.figure()

ax1 = fig.add_axes([0, 0, 1, 1])
ax2 = fig.add_axes([0.5, 0.5, 0.5, 0.5])

ax1.plot(x, y1, 'r')
ax2.plot(x, y2, 'b')
```





    [<matplotlib.lines.Line2D at 0x24a8ceebd00>]




    
![png](https://imgbed.kouseki.cn/file/2a49cb663f2915594e888.png)
    


### 2、三维图形绘制

* 绘制一个薄圆柱体。


```python
from mpl_toolkits import mplot3d

t = np.linspace(0, 2*np.pi, 1000)
X = np.sin(t)
Y = np.cos(t)
Z = np.arange(t.size)[:, np.newaxis]

ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
```





    <mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x24a8dff2d30>




    
![png](https://imgbed.kouseki.cn/file/cecb4aae947e84e5da3ac.png)
