Matplotlib入门篇,也可以很酷炫

开发 后端
哈喽,大家好。今天写一篇 Matplotlib 的入门教程。Matplotlib 是 Python 数据可视化库,广泛应用在数据分析和机器学习中。

[[441338]]

哈喽,大家好。今天写一篇 Matplotlib 的入门教程。

Matplotlib 是 Python 数据可视化库,广泛应用在数据分析和机器学习中。

1. 第一张图

Matplotlib 支持面向对象和pyplot接口两种方式画图。

以这两种方式为例,画出如下图所示的函数图。

y=x^2

面向对象方式

  1. import matplotlib.pyplot as plt 
  2. import numpy as np 
  3.  
  4. x = np.linspace(0, 2, 100) 
  5.  
  6. fig, ax = plt.subplots() 
  7. ax.plot(x, x**2) # 折线图 
  8. ax.set_xlabel('x') # 设置横坐标名称 
  9. ax.set_ylabel('y') # 设置纵坐标标签 
  10. ax.set_title("y = x^2") # 设置标题 
  11.  
  12. plt.show() 

plt.subplots() 函数返回fig和ax,分别是Figure对象和Axes对象。前者代表画布,后者代表画布上的绘图区域,很显然画布和绘图区域是一对多的关系。

之后关于绘图的设置,都通过Axes对象完成。

pyplot方式

  1. import matplotlib.pyplot as plt 
  2. import numpy as np 
  3.  
  4. x = np.linspace(0, 2, 100) 
  5.  
  6. plt.figure() 
  7. plt.plot(x, x**2) 
  8. plt.xlabel('x'
  9. plt.ylabel('y'
  10.  
  11. plt.show() 

pyplot方式绘图和设置都通过plt来完成,没有对象的概念。

虽然这两种方式都能画图,但官方更建议采用面向对象的方式。

2. 支持多种图形

除了上面例子中看到的折线图,Matplotlib 还支持以下图形:

  • stackplot:堆叠图
  • bar/barh:柱状图
  • hist:直方图
  • pie:饼形图
  • scatter:散点图
  • contourf:等高线图
  • boxplot:箱型图
  • violinplot:提琴图

另外,Matplotlib 还是支持 3D 绘图

3. 常见设置

在第一小节的例子里,我们通过set_xlabel和set_title设置坐标轴名称和标题。

除此之外,还可以添加注释和图例。

  1. x = np.linspace(0, 2, 100) 
  2.  
  3. fig, ax = plt.subplots() 
  4. ax.plot(x, x**2, label='二次函数'
  5. ax.set_xlabel('x'
  6. ax.set_ylabel('y'
  7. ax.set_title("y = x^2"
  8.  
  9. # 添加注释 
  10. ax.annotate('坐标(1,1)', xy=(1, 1), xytext=(0.5, 1.5), 
  11.             arrowprops=dict(facecolor='black', shrink=0.05)) 
  12. # 添加图例 
  13. ax.legend() 

还可以设置坐标轴的格式

  1. ax.xaxis.set_major_formatter('x坐标{x}'

如果坐标轴是日期会非常有用,可以将日期转成周、月、季度等格式。

4. 一个画布多图形前面提到过,一个画布可以有多个绘图区域。

下面使用plt.subplots()函数可以创建2行2列,4个绘图区域。

  1. import matplotlib.pyplot as plt 
  2. import numpy as np 
  3.  
  4. fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(5.5, 3.5), 
  5.                         constrained_layout=True
  6. add an artist, in this case a nice label in the middle... 
  7. for row in range(2): 
  8.     for col in range(2): 
  9.         axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5), 
  10.                                transform=axs[row, col].transAxes, 
  11.                                ha='center', va='center', fontsize=18, 
  12.                                color='darkgrey'
  13. fig.suptitle('plt.subplots()'

也可以通过subplot_mosaic()函数创建

  1. fig, axd = plt.subplot_mosaic([['upper left''upper right'], 
  2.                                ['lower left''lower right']], 
  3.                               figsize=(5.5, 3.5), constrained_layout=True
  4. for k in axd: 
  5.     annotate_axes(axd[k], f'axd["{k}"]', fontsize=14) 
  6. fig.suptitle('plt.subplot_mosaic()'

通过subplot_mosaic()函数,还可以将其他几个绘图区域合并成一个。

  1. fig, axd = plt.subplot_mosaic([['upper left''right'], 
  2.                                ['lower left''right']], 
  3.                               figsize=(5.5, 3.5), constrained_layout=True
  4. for k in axd: 
  5.     annotate_axes(axd[k], f'axd["{k}"]', fontsize=14) 
  6. fig.suptitle('plt.subplot_mosaic()'

通过 GridSpec 也可以创建更复杂的绘图区域。

  1. fig = plt.figure(constrained_layout=True
  2. gs0 = fig.add_gridspec(1, 2) 
  3.  
  4. gs00 = gs0[0].subgridspec(2, 2) 
  5. gs01 = gs0[1].subgridspec(3, 1) 
  6.  
  7. for a in range(2): 
  8.     for b in range(2): 
  9.         ax = fig.add_subplot(gs00[a, b]) 
  10.         annotate_axes(ax, f'axLeft[{a}, {b}]', fontsize=10) 
  11.         if a == 1 and b == 1: 
  12.             ax.set_xlabel('xlabel'
  13. for a in range(3): 
  14.     ax = fig.add_subplot(gs01[a]) 
  15.     annotate_axes(ax, f'axRight[{a}, {b}]'
  16.     if a == 2: 
  17.         ax.set_ylabel('ylabel'
  18.  
  19. fig.suptitle('nested gridspecs'

5. 高级用法

Matplotlib 很强大,设置很灵活,比如,折线图可以用极坐标画图

稍加改造还可以画出玫瑰图。

折线图隐藏坐标轴和边框,再结合注释就可以画出时间轴

多图组合形成更复杂的统计图

Matpolitlib还支持图形动画和交互式。

今天这篇文章只介绍了 Maptplotlib 很初级的一部分内容,它本身内容非常丰富、也很复杂。后面有机会我们可以介绍更深入的内容。

 

如果本文对你有用就点个 在看 鼓励一下吧。

 

责任编辑:武晓燕 来源: 渡码
相关推荐

2017-09-12 10:26:47

springbootmaven结构

2011-01-18 17:00:31

Postfix入门

2020-11-16 10:19:33

Java

2016-09-06 17:43:12

SwiftCloudKit开发

2009-06-09 13:02:30

NetBeans使用教程

2022-03-28 09:31:58

for循环语句

2015-07-30 09:43:10

独立游戏开发入门

2022-01-27 09:35:45

whiledo-while循环Java基础

2012-01-17 10:47:07

jQuery

2020-11-13 07:22:46

Java基础While

2022-07-06 07:57:37

Zookeeper分布式服务框架

2020-11-19 10:36:16

Java基础方法

2020-11-09 10:19:05

Java

2022-03-10 09:33:21

Java数组初始化

2010-09-08 13:42:06

2009-06-15 17:22:36

JBoss Seam

2018-12-21 12:25:08

2017-01-22 21:30:39

大数据Kaggle函数

2010-07-26 11:09:35

Perl函数手册

2020-10-22 13:33:48

Java基础入门
点赞
收藏

51CTO技术栈公众号