Matplotlib多图

Matplotlib多图

Matplotlib多图

  Matplotlib 是一个用于创建静态、动画和交互式可视化的 Python 库。它可用于创建各种绘图,包括折线图、条形图、散点图和直方图。

  Matplotlib 提供了多种在单个图中创建多个子图的方法。一种方法是使用该subplot()函数。该subplot()函数接受两个或三个参数:行数、列数和子图的索引,本文中我们晓得博客将介绍Matplotlib多图学习如何在同一画布上创建多个子图。

  推荐:Matplotlib Axes轴类

创建子图

  subplot ()函数返回给定网格位置的坐标区对象。该函数的调用签名是 –

plt.subplot(subplot(nrows, ncols, index)

  在当前图中,该函数创建并返回一个 Axes 对象,位于 nrows x ncolsaxes 网格的位置索引处。索引从 1 到 nrows * ncols,按行主序递增。如果 nrows、ncols 和索引都小于 10。索引也可以以单个、串联、三位数的形式给出。

  例如, subplot(2, 3, 3) 和 subplot(233) 都在当前图窗的右上角创建一个轴,占据图窗高度的一半和图窗宽度的三分之一。

  创建子图将删除与其重叠但超出共享边界的任何预先存在的子图。

import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid with 2 rows and 1 column.
#Since this subplot will overlap the first, the plot (and its axes) previously ax.remove()
plt.clf()
plt.subplot(211)
plt.plot(range(12))
plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background
plt.plot(range(12))

  上面的代码行生成以下输出 –

Matplotlib多图

  推荐:Matplotlib Figure Class图类

  图类的 add_subplot() 函数不会覆盖现有图 –

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot([1,2,3])
ax2 = fig.add_subplot(221, facecolor='y')
ax2.plot([1,2,3])

  当执行上面的代码行时,它会生成以下输出 –

Matplotlib多图

  推荐:Matplotlib简单绘图

  您可以通过在同一图形画布中添加另一个坐标区对象来在同一图形中添加插入图。

import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig=plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes
y = np.sin(x)
axes1.plot(x, y, 'b')
axes2.plot(x,np.cos(x),'r')
axes1.set_title('sine')
axes2.set_title("cosine")
plt.show()

  执行上述代码行后,将生成以下输出 –

Matplotlib多图

  推荐:Python最佳IDE集成开发环境

  推荐:Matplotlib教程


晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Matplotlib多图

转载请保留链接:https://www.pythonthree.com/matplotlib-multiplots/

滚动至顶部