PythonGuides 博客中文翻译(三十八)

原文:PythonGuides Blog

协议:CC BY-NC-SA 4.0

matplotlib tight _ layout–有用的教程

原文:https://pythonguides.com/matplotlib-tight-layout/

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

在本 Python Matplotlib 教程中,我们将讨论 Python 中的 Matplotlib tight_layout 。在这里,我们将使用 matplotlib 介绍与紧密布局相关的不同示例。我们还将讨论以下主题:

  • Matplotlib tick_layout
  • Matplotlib tight_layout 示例
  • Matplotlib 紧密布局焊盘
  • Matplotlib 紧密布局 hspace
  • Matplotlib 紧密布局 wspace
  • Matplotlib 紧密布局矩形
  • Matplotlib tight_layout 保存图
  • Matplotlib tight_layout 子情节
  • Matplotlib tight_layout suptitle
  • Matplotlib tight_layout 剪切标签
  • Matplotlib 紧密布局图例
  • Matplotlib 紧密布局 bbox
  • Matplotlib tight_layout 未应用
  • Matplotlib tight_layout rcparams
  • Matplotlib imshow tight_layout
  • Matplotlib tight_layout gridspec
  • Matplotlib tight_layout 颜色条
  • Matplotlib 表格紧密布局
  • Matplotlib 散点图紧密布局
  • Matplotlib 3d plot tight layout
  • Matplotlib undo tight_layout
  • Matplotlib 紧密布局替代方案
  • Matplotlib constrained_layout 与 tight_layout

目录

Matplotlib tick_layout

在本节中,我们将学习 Python 中 matplotlib 的 pyplot 模块中的 tick_layout ()函数。 tick_layout 方法用于自动调整支线剧情。或者我们可以说,这个方法是用来调整子情节之间和周围的填充的。

语法如下:

matplotlib.pyplot.tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None)

以下是上面使用的参数:

| 参数 | | 默认值 | 描述 |
| 衬垫 | 漂浮物 | One point zero eight | 此参数用于指定人物边缘和子情节边缘之间的填充,作为字体大小的一部分。 |
| h_pad, w_pad | 漂浮物 | 衬垫 | 此参数用于指定相邻子情节边缘之间的高度或粗细,作为字体大小的一部分。 |
| 矩形 | 元组(左、下、右、上) | (0, 0, 1, 1) | 该参数用于在标准化图形坐标中指定一个矩形,包括标签在内的整个子图形区域将适合该矩形。 |

tight_layout

我们使用 tight_layout()函数的不同情况:

  • 当轴标签或标题超出图形区域时。
  • 当不同子情节的轴标签或标题相互重叠时。
  • 当我们在图形区域有多个支线剧情,并且每个都有不同的大小时。
  • 当我们想要调整人物周围和支线剧情之间的额外填充时。

阅读Python Matplotlib tick _ params+29 示例

Matplotlib tight_layout 示例

有时在多个支线剧情的情况下,我们会看到标签、标记、标题、图例等互相重叠。

在 matplotlib 中,为了避免重叠,或者我们可以说,为了调整子情节之间的间距,我们可以使用 tight_layout() 函数。

这个函数( tight_layout )的主要目的是最小化重叠,而不是剪切它们。

我们来看一个例子:

代码#1:正常绘图

**# Import Library** 
import numpy as np 
import matplotlib.pyplot as plt 

**# Create figure and subplot** 
fig, ax = plt.subplots(1, 2) 

**# Define  Data** 
x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

**# PLot Subplot 1** 
ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

**# Add legend** 
ax[0].legend(loc='upper left')

**# Define Data** 
y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

**# plot subplot 2** 
ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

**# Add legend** 
ax[1].legend(loc='upper right')

**# Show** 
plt.show() 
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 包。
  • 接下来,我们使用 subplots() 方法创建一个图形和一组 subplots。
  • 之后,我们为子图 1 和子图 2 定义数据坐标,并使用 plot() 方法绘制数据。
  • 为了放置每个子情节的图例,我们添加了标签,并且为了激活每个曲线的标签,我们使用了 legend() 方法。
  • 要显示该图,请使用 show() 方法。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Normal PLot

上面的代码#1 只是一个简单的 matplotlib 子情节代码,其中我们在一个图形区域中有多个子情节。

代码#2:紧密布局

**# Import Library** 
import numpy as np 
import matplotlib.pyplot as plt 

**# Create figure and subplot** 
fig, ax = plt.subplots(1, 2) 

**# Define  Data** 
x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

**# PLot Subplot 1** 
ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

**# Add legend** 
ax[0].legend(loc='upper left')

**# Define Data** 
y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

**# Plot subplot 2** 
ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

**# Add legend** 
ax[1].legend(loc='upper right')

**# tight_layout** 
plt.tight_layout() 

**# Show** 
plt.show() 

在这个例子中,我们还使用了 tight_layout() 函数来调整图形的标签,而不是剪切它们。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout()

在上面的代码#2 中,我们要实现 tight_layout() 函数。

读取 Matplotlib x 轴标签

Matplotlib tight _ layout pad

我们将学习如何调整人物边缘和支线剧情边缘之间的填充。为了调整它们,我们使用参数。

以下是语法:

matplotlib.pyplot.tight_layout(pad=1.08)

举例:

**# Import Libraries**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplot**

fig, ax = plt.subplots(2, 2)

**# Define Data**

data = np.arange(0.0, 30, 0.05)

x1= np.sin(data) 
y1= np.cos(data)

x2= np.cos(data)
y2= np.tan(data)

x3= np.tan(data)
y3= np.exp(data*2)

x4= [5,10,15]
y4= [6,12,18]

**# Plot curves or subplots**

ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

**# Add title to graph**

ax[0, 0].set_title("Graph 1 ")
ax[0, 1].set_title("Graph 2")
ax[1, 0].set_title("Graph 3")
ax[1, 1].set_title("Graph 4")

**# tight_layout** 
plt.tight_layout(pad=3.68)

**# Show**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 包。
  • 接下来,我们使用 subplots() 方法创建一个图形和一组 subplots。
  • 之后,我们为多个子图定义数据坐标,并使用 plot() 方法绘制数据。
  • 通过使用 set_title() 方法,我们为每个情节添加标题。
  • 要调整填充,请使用 plt.tight_layout() 方法。我们将 pad 作为参数传递,并在各自的情况下将它们赋值为 3.685.86

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout(pad=3.68)

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout(pad=5.86)

读取 Matplotlib 多条形图

Matplotlib tight _ layout hspace

我们将学习如何调整相邻支线剧情边缘之间的高度。为了调整高度,我们将 h_pad 参数传递给 tight_layout() 方法。

以下是语法:

matplotlib.tight_layout(h_pad=None)

我们来看一个例子:

**# Import Libraries**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplot**

fig, ax = plt.subplots(2, 1)

**# Define Data** 
data = np.arange(0.0, 30, 0.05)

x1= np.sin(data) 
y1= np.cos(data)

x2= np.cos(data)
y2= np.tan(data)

**# Plot curves or subplots**

ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

**# Add title to graph**

ax[0].set_title("Graph 1 ")
ax[1].set_title("Graph 2")

**# tight_layout** 
plt.tight_layout(h_pad=0.2)

**# Show**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 包。
  • 之后,我们使用 subplots() 方法创建一个图形和一组支线剧情。
  • 我们为多个子图定义数据坐标,并使用 plot() 方法绘制数据。
  • 通过使用 set_title() 方法,我们为每个情节添加标题。
  • 要调整边缘之间的高度,请使用 plt.tight_layout() 方法。我们将 h_pad 作为参数传递,并在各自的情况下将它们赋值为 1.5 和 15.5。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout(h_pad=1.5)

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout(h_pad=15.5)

阅读 Matplotlib 散点图图例

Matplotlib tight _ layout wspace

我们将学习如何调整相邻支线剧情边缘之间的宽度。为了调整宽度,我们将 w_pad 参数传递给 tight_layout() 方法。

以下是语法:

matplotlib.tight_layout(w_pad=None)

我们来看一个例子:

**# Import Libraries**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplot**

fig, ax = plt.subplots(1, 2)

**# Define Data**

data = np.arange(0.0, 30, 0.05)

x1= np.sin(data) 
y1= np.cos(data)

x2= np.exp(data*2)
y2= np.tan(data)

**# Plot curves or subplots** 
ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

**# Add title to graph** 
ax[0].set_title("Graph 1 ")
ax[1].set_title("Graph 2")

**# tight_layout**

plt.tight_layout(w_pad=5.5)

**# Show**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 包。
  • 之后,我们使用 subplots() 方法创建一个图形和一组支线剧情。
  • 我们为多个子图定义数据坐标,并使用 plot() 方法绘制数据。
  • 通过使用 set_title() 方法,我们为每个情节添加标题。
  • 要调整边缘之间的宽度,使用 plt.tight_layout() 方法。我们将 w_pad 作为参数传递,并赋予它们 5.5 值。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout()

这里我们使用 tight_layout() 方法**,没有 w_pad** 参数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout(w_pad=5.5)

这里我们使用带有 w_pad 参数的 tight_layout() 方法**。**

读取 Matplotlib 3D 散点图

Matplotlib tight _ layout rect

我们将学习如何在标准化图形坐标中指定一个矩形,包括标签在内的整个支线剧情区域都将适合这个矩形。

以下是语法:

matplotlib.pyplot.tight_layout(rect=(0, 0, 1, 1)

我们来看一个例子:

**# Import Library** 
import numpy as np 
import matplotlib.pyplot as plt 

**# Create figure and subplot**

fig, ax = plt.subplots(1, 2) 

**# Define  Data**

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

**# PLot Subplot 1**

ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

**# Add legend**

ax[0].legend(loc='upper left')

**# Define Data** 
y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

**# Plot subplot 2**

ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

**# Add legend**

ax[1].legend(loc='upper right')

**# tight_layout**

fig.tight_layout(rect=(1.5, 0.86, 4.23, 2.55)) 

**# Show**

plt.show() 
  • 在示例中,我们使用了 arange()sin()cos()tan()exp() 函数来定义数据。
  • 要绘制图形,请使用 plt.plot() 方法。
  • 为了放置每个支线剧情的图例,我们添加了 标签 并激活每个曲线的标签,我们使用了 legend() 方法。
  • 使用带有矩形参数的 tight_layout() 方法。我们传递一个值为 1.5,0.86,4.23,2.55 的元组。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Simple Plot Without tight_layout()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout()

读取堆积条形图 Matplotlib

Matplotlib tight _ layout save fig

有时,我们会在创建的图形上看到大边框。为了获得自动调整大小的边框,我们使用了 tight_layout() 函数。

举例:

**# Import Library**

import numpy as np 
import matplotlib.pyplot as plt 

**# Define  Data**

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

**# Plot**

plt.plot(x, y1, label='Line1') 
plt.plot(x, y2, marker ='o', label='Line2') 

**# tight_layout**

plt.tight_layout()

**# Savefig**

plt.savefig('SimplePlot.png')

**# Show**

plt.show() 
  • 在上面的例子中,我们使用了 tight_layout() 方法来调整绘图的边界。
  • 使用 plt.savefig() 方法将图形保存为 png

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

savefig()

当我们在不使用 tight_layout 函数的情况下保存绘图时,会出现上面的输出。这里我们得到了额外的边界。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

savefig() with tight_layout()

读取 Matplotlib 两个 y 轴

Matplotlib tight_layout 支线剧情

matplotlib 库中的 tight_layout 函数用于自动调整子情节之间的适当间距,使其适合图形区域而不被切割。

我们来看一个例子:

**# Importing library**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplots** 
fig, ax = plt.subplots(3,1)

**# Define Data**

x1= [2,4,6]
y1= [3,6,9]

x2= [5,10,15]
y2= [6,12,18]

x3= [2,4,6]
y3= [3,6,9]

**# Plot lines**

ax[0].plot(x1, y1)
ax[1].plot(x2, y2)
ax[2].plot(x3, y3)

**# Add title**

ax[0].set_title("Graph 1 ")
ax[1].set_title("Graph 2")
ax[2].set_title("Graph 3")

**# Auto adjust**

plt.tight_layout()

**# Display**

plt.show()
  • 在上面的例子中,我们创建了 3 行 1 列的图形和支线剧情。
  • 之后,我们定义数据坐标,并使用 plot() 方法在它们之间绘制一条线。
  • set_title() 方法用于添加标题。
  • 为了消除重叠或者自动调整支线剧情,我们使用了 tight_layout() 方法。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

“Plot Without tight_layout() method”

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

“Subplots with tight_layout() function”

又念,水平线 matplotlib

Matplotlib tight _ layout sup title

有时候,剧情的 suptitle 和 title 互相重叠,剧情看起来不整洁。我们将学习如何自动调整情节的标题。

举例:

**# Import Library** 
import numpy as np
import matplotlib.pyplot as plt

**# Create figure**

fig = plt.figure()

**# Define Data** 
x = np.random.randint(10,size=500)
y = np.random.random(500)

**# Add sup tile**

fig.suptitle('SUPTITLE', fontsize=24)

**# Create subplot 1**

plt.subplot(121)

**# Plot line**

plt.plot(x)

**# Add Title**

plt.title('RANDINT PLOT', fontsize=15)
 **# Create subplot 2**

plt.subplot(122)

**# Plot line** 
plt.plot(y)

**# Add Title**

plt.title('RANDOM PLOT', fontsize=15)

**# Auto adjust**

plt.tight_layout()

**# Dispaly**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 模块。
  • 接下来,我们使用 plt.figure() 方法创建一个图形。
  • 之后,我们使用 randint()random() 方法定义数据。
  • 然后,我们通过使用 fig.suptitle() 方法向该图添加一个标题。
  • plt.subplots() 方法用于在一个图区域中创建支线剧情。
  • 要绘制数据坐标之间的直线,使用 plt.plot() 方法。
  • 要给绘图添加标题,使用 plt.title() 方法。
  • 要消除标题重叠,请使用 tight_layout() 函数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

“Overlap title plot”

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout()

读取绘制垂直线 matplotlib

Matplotlib tight_layout 切割标签

有时,图的 x 轴标签和 y 轴标签相互重叠,图看起来不整洁。我们将学习如何自动调整图的标签。

我们来看一个例子:

**# Importing library** 
import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplots**

fig, ax = plt.subplots(2,2, figsize=(8, 5))

**# Define Data**

x1= np.random.randint(10,size=500)

x2= [5,10,15]
y2= [6,12,18]

x3= np.arange(0.0, 30.0 , 0.02) 
y3= np.tan(x3)

x4 = np.arange(0.0, 30.0 , 0.02) 
y4 = np.sin(x4)

**# Plot lines** 
ax[0, 0].plot(x1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

**# Add xlabel** 
ax[0, 0].set_xlabel('X-Axis')
ax[1, 0].set_xlabel('X-Axis')
ax[0, 1].set_xlabel('X-Axis')
ax[1, 1].set_xlabel('X-Axis')

**# Add ylabel**

ax[0, 0].set_ylabel('Y-Axis')
ax[1, 0].set_ylabel('Y-Axis')
ax[0, 1].set_ylabel('Y-Axis')
ax[1, 1].set_ylabel('Y-Axis')

**# Auto adjust**

plt.tight_layout()

**# Display**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 库。
  • 之后,我们使用**支线剧情()**方法创建人物和支线剧情。
  • 然后我们定义数据坐标,并用 plt.plot() 方法在它们之间画一条线。
  • set_xlabel()set_ylabel() 方法分别用于在 x 轴和 y 轴添加标签。
  • 要自动调整绘图,请使用 tight_layout() 函数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

“Overlap labels”

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout()

检查完毕, Matplotlib 反转 y 轴

Matplotlib tight_layout 图例

有时,当我们在机器中保存一个带有图例的图时,我们发现图例被截断了。所以,我们将学习如何解决在保存一个情节时图例被切断的问题。

为了避免图例的截断,请使用 matplotlib 的 pyplot 模块的 tight_layout() 方法。

我们来看一个例子:

**# Import Library**

import matplotlib.pyplot as plt

**# Create figure**

fig = plt.figure(1)

**# Plot**

plt.plot([1, 2, 3, 4, 5], [1, 0, 1, 0, 1], label='A label')
plt.plot([1, 2, 3, 8, 2.5], [1, 2, 2, 1, 0], label='B label')

**# Legend**

plt.legend(loc='center left', bbox_to_anchor=(1, 0))

**# Savefig**

#fig.savefig('Cut-off Legend.png')

**# Display**

plt.show()
  • 这里我们导入 matplotlib.pyplot 库,使用 plt.figure() 创建图形。
  • 之后,我们绘制图表并定义标签。
  • 然后我们使用 plt.legend() 方法在图中添加一个图例。并且我们传递 loc 和 bbox_to_anchor 参数,分别设置它们的值中左,和 1,0
  • 使用 savefig() 方法在机器中保存图形。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

” Jupyter Notebook Output “

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

” Savefig Output “

在上面的输出中,我们看到当我们使用 savefig() 方法在机器中保存绘图时,l egends 被切断

为了克服这个问题,我们使用了 tight_layout() 方法。

举例:

**# Import Library**

import matplotlib.pyplot as plt

**# Create figure** 
fig = plt.figure(1)

**# Plot**

plt.plot([1, 2, 3, 4, 5], [1, 0, 1, 0, 1], label='A label')
plt.plot([1, 2, 3, 8, 2.5], [1, 2, 2, 1, 0], label='B label')

**# Legend**

plt.legend(loc='center left', bbox_to_anchor=(1, 0))

**# Adjust legend**

plt.tight_layout()

**# Savefig**

fig.savefig('Proper Legend.png')

**# Display**

plt.show()

现在,这里我们使用 plt.tight_layout() 方法,用于自动调整绘图、标记标签、标签和图例。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout()

在上面的输出中,我们使用 tight_layput() 方法来获得正确的图例。

读取将图例放在绘图 matplotlib 外

matplotlibb TIG _ layout bbox

在本节中,我们将学习在系统中保存地块时如何避免重叠、截断和额外空间。save fig()方法的 bbox_inches 参数和 matplotlib 的 tight_layout() 方法帮助你克服这个问题。

我们来看一个例子:

**# Importing library**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplots**

fig, ax = plt.subplots(2,1, figsize=(8, 5))

**# Define Data**

x1= np.random.randint(10,size=500)

x2= np.arange(0.0, 30.0 , 0.02) 
y2= np.tan(x2)

**# Plot lines**

ax[0].plot(x1)
ax[1].plot(x2, y2)

**# Add sup tile**

fig.suptitle('SUPTITLE', fontsize=24)

**# Add xlabel**

ax[0].set_xlabel('X-Axis')
ax[1].set_xlabel('X-Axis')

**# Add ylabel**

ax[0].set_ylabel('Y-Axis')
ax[1].set_ylabel('Y-Axis')

**# Auto adjust**

plt.tight_layout()
fig.savefig('tight_layout bbox.png', bbox_inches='tight')

**# Display**

plt.show()
  • 在上面的例子中,为了定义数据坐标,我们使用了 randint()arange()tan() 方法。
  • 之后,为了创建绘图曲线,我们使用了 plot() 方法。
  • suptitle() 方法用于给情节添加标题。
  • set_xlabel()set_yalbel() 方法用于分别在 x 轴和 y 轴添加标签。
  • plt.tight_layout() 方法是自动调整支线剧情。
  • 我们将 bbox_inches 参数传递给 savefig() 方法,并将其值设置为“tight”,因为它移除了多余的边框。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Overlapped Plot

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout() and bbox_inches =’tight’

签出, Matplotlib 另存为 pdf + 13 示例

Matplotlib tight_layout 未应用

在某些情况下, tight_layout() 方法不能正常工作。在第节中,我们将学习在这种情况下我们必须做什么。

让我们借助一个例子来理解整个概念:

**# Import Library** 
import matplotlib.pyplot as plt

**# Create figure** 
fig = plt.figure(1)

**# Define Data** 
data = np.arange(0.0, 30.0 , 0.02) 
x1 = np.sin(data)
x2 = np.cos(data)

**# Plot** 
plt.plot(data, x1, label='Sin')
plt.plot(data, x2, label='Cos')

**# Add legend** 
plt.legend(loc='center left', bbox_to_anchor=(0.8,-0.1))

**# tight_layout** 
plt.tight_layout()

**# display**

plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

从上面的例子中,我们得出结论, tight_layout() 方法不起作用,因为图例与 ticklabels 重叠。

**解决方案:**使用 tight_layout() 配合 rect 参数。

代码:

**# Import Library** import matplotlib.pyplot as plt

import numpy as np

**# Create figure**

fig = plt.figure(1)

**# Define Data** 
data = np.arange(0.0, 30.0 , 0.02) 
x1 = np.sin(data)
x2 = np.cos(data)

**# Plot**

plt.plot(data, x1, label='Sin')
plt.plot(data, x2, label='Cos')

**# Add legend**

plt.legend(loc='center left', bbox_to_anchor=(0.8,-0.1))

**# tight_layout with rect** 
plt.tight_layout(rect=(1.5, 0.86, 3.23, 2.55))

**# display**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplot 库,并使用 plt.figure() 创建了一个图形。
  • 之后,我们使用 numpy 的 arange()sin()cos() 方法定义数据。
  • 为了绘制数据,使用 matplotlib pyplot 模块的 plot() 方法。
  • 为了放置图例,我们添加了 标签 并激活每条曲线的标签,我们使用了 legend() 方法。
  • 为了恰当地适应包括标签在内的子情节区域,我们使用带有矩形参数的紧密布局方法。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout(rect=())

阅读什么是 matplotlib 内联

Matplotlib tight _ layout RC params

matplotlib.pyplot.tight_layout()方法仅在被调用时自动调整子情节。如果希望每次重新绘制图形时,都必须进行这种更改,请设置 rcParams。

语法如下:

rcParams["figure.autolayout]

默认情况下,其值为 False。将其设置为 True。

我们来看一个例子:

**# Importing library** 
import numpy as np
import matplotlib.pyplot as plt

**# Default adjustment** 
plt.rcParams["figure.autolayout"] = True

**# Create figure and subplots**

fig, ax = plt.subplots(2,1, figsize=(8, 5))

**# Define Data**

x1= [0, 1, 2, 3, 4]
y1= [2.5, 3.5, 4.5, 6.3, 2.1]

x2= [2, 4, 8, 3, 1]
y2= [5.2, 6, 1, 2.6, 9]

**# Plot lines**

ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

**# Add sup tile**

fig.suptitle('SUPTITLE', fontsize=24)

**# Add xlabel**

ax[0].set_xlabel('X-Axis')
ax[1].set_xlabel('X-Axis')

**# Add ylabel**

ax[0].set_ylabel('Y-Axis')
ax[1].set_ylabel('Y-Axis')

**# Display**

plt.show()

在上面的例子中,我们使用**RC params[" figure . autolayout "]**而不是 tight_layout() 的方法来调整支线剧情,并将其设置为值 True

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.rcParams[“figure.autolayout”]

举例:

**# Import Library**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure** 
fig = plt.figure()

**# Define Data**

x = np.random.randint(10,size=500)
y = np.random.random(500)

**# Add sup tile**

fig.suptitle('SUPTITLE', fontsize=24)

**# Create subplot 1**

plt.subplot(121)

**# Plot line** 
plt.plot(x)

**# Add Title**

plt.title('RANDINT PLOT', fontsize=15)

**# Create subplot 2**

plt.subplot(122)

**# Plot line** 
plt.plot(y)

**# Add Title** 
plt.title('RANDOM PLOT', fontsize=15)

**# Dispaly**

plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

现在,看上面的例子,我们没有使用任何方法来调整支线剧情。它会自动调整支线剧情,因为我们在前面的例子中使用了 rcParams[] 。因此,每次重新绘制图形时,它都会自动调整。

阅读 Python 使用 Matplotlib 绘制多行

Matplotlib imshow tight _ layout

我们将学习如何使用 tight_layout 方法和 imshow() 方法。首先我们了解什么是 imshow() 函数。

【imshow()】函数用于将数据显示为图像。

*tick_layout 方法与 imshow() 方法一起使用,自动调整绘图。

举例:

**# Import Library**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplot**

fig = plt.figure(figsize=(8,5))
ax = plt.subplot(111)

**# Define Data**

arr = np.arange(100).reshape((10,10))

**# Title**

fig.suptitle('imshow() function Example', fontweight ="bold", fontsize= 24)

**# plot**

im = ax.imshow(arr, interpolation="none")

**# adjsut** 

plt.tight_layout()

**# Visualize**

plt.show() 
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpy 库。
  • 在此之后,我们分别使用**图()支线剧情()**的方法创建和支线剧情,
  • 然后我们使用 arange() 方法定义数据,并使用 reshape() 方法对其进行整形。
  • 为了给图添加一个 suptitle,我们使用 suptitle() 方法。我们将字体大小字体重量作为参数传递。
  • 然后我们使用 imshow() 方法绘制图形,使用 tight_layout() 方法自动调整图形。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

imshow()

读取 Matplotlib 绘制一条线

Matplotlib tight _ layout grid spec

我们将学习如何对 GridSpec 类使用 tight_layout() 方法。首先了解什么是 GridSpec 类。

matplotlib.grispec.GridSpec 类用于指定放置子图的网格的几何形状。必须设置行数和列数。

GridSpec 类的语法如下:

matplotlib.gridspec.GridSpec(nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratio=None, height_ratio=None)

GridSpec 有自己的 tight_light() 方法。pyplot 的 tight_layout() 方法也适用于它。我们也可以使用指定边界框的矩形参数。 h_padw_pad 参数用于调整绘图的顶部和底部。

我们来看一个例子:

**# Import Library**

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

**# Create figure**

fig = plt.figure(figsize =([9, 5]))

**# GridSpec**

gs = gridspec.GridSpec(2, 6)

**# Subplots**

ax1 = plt.subplot(gs[0, :2])
ax1.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax1.plot([0, 1, 2], [2, 3.6, 4])

ax2 = plt.subplot(gs[0, 2:4])
ax2.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax2.plot([2, 5.5, 9], [2, 3.6, 4])

ax3 = plt.subplot(gs[1, 1:3])
ax3.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax3.plot([0, 1, 2], [1, 2, 3])

ax4 = plt.subplot(gs[1, 3:5])
ax4.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax4.plot([2.3, 4.6, 8.8, 9.6], [4.2, 5.5, 6, 4])

**# Auto adjust**

plt.tight_layout()

**# Display**

plt.show() 
  • 在上面的例子中,我们 pyplotGridSpecmatplotlib 的类。
  • 为了创建一个图,我们使用 figure() 方法。
  • 之后,我们使用 GridSpec() 方法创建网格来放置子情节。
  • 为了在 y 轴上设置标签,我们使用了 set_yalbel() 方法。
  • 然后我们用 tight_layout() 的方法自动调整支线剧情。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Overlapped Subplots

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout()

读取 Matplotlib 旋转刻度标签

Matplotlib tight _ layout color bar

我们将学习如何使用 tight_layout() 方法和 colorbar() 方法。一个 colorbar() 方法被用来给绘图添加一个颜色条。

colorbar()方法的语法如下:

matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kw)

举例:

**# Import Library**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplot**

fig = plt.figure(figsize=(8,5))
ax = plt.subplot(111)

**# Define Data**

arr = np.arange(100).reshape((10,10))

**# Plot**

im = ax.imshow(arr, interpolation="none")

**# Add colorabar**

plt.colorbar(im)

**# adjsut** 

plt.tight_layout()

**# Visualize**

plt.show()
  • 在这里,我们使用 numpy 的 arange() 方法定义数据,然后使用 reshape() 方法重塑图形。
  • 之后,我们使用 imshow() 方法绘制图形。
  • 要将 colorbar 添加到绘图中,请使用 colorbar() 方法。
  • tight_layout() 方法用于自动调整情节。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.colorbar()

读取 Matplotlib 改变背景颜色

Matplotlib 表紧 _ 布局

我们将学习如何在图形区域内自动调整图和表,而不发生重叠。在 matplotlib 中通过使用matplotlib . py plot . table()方法我们可以创建一个表格。

创建表格的语法如下:

matplotlib.pyplot.table(cellText=None, cellColours=None, 
                        cellLoc=’right’,colWidths=None,
                        rowLabels=None, rowColours=None, 
                        rowLoc=’left’,colLabels=None, 
                        colColours=None, colLoc=’center’, 
                        loc=’bottom’, bbox=None, 
                        edges=’closed’, **kwargs) 

我们来看一个例子:

**# Import Library**

import numpy as np
import matplotlib.pyplot as plt

**# Define data**

data = np.random.rand(3, 2)
columns = ('Col1', 'Col2')
rows = ['# %d' % p for p in (1, 2, 3)] 

**# Plot data**

plt.plot(data)

**# X-axis** 

plt.xlabel('X-axis')

**# Define table** 
the_table = plt.table(cellText=data,rowLabels=rows, colLabels=columns,loc='bottom', bbox=[0,-0.55,1,.33])

**# auto adjust**

plt.tight_layout()

**# Display**

plt.show()
  • 这里我们导入 numpymatplotlib.pyplot 库。
  • 接下来,我们使用 random.rand() 方法定义数据,我们还定义了列和行。
  • 通过使用 plt.plot() 我们创建一个图形,并使用 plt.xlabel() 方法定义其 x 轴标签。
  • 要生成表格,请使用 matplotlib 的 table() 方法,带有 cellTextrowLabelscolLabelslocbbox 参数。
  • 为了避免重叠,并使绘图整洁,我们使用了 tight_layout() 方法。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout()

检查, Matplotlib 散点图标记

Matplotlib 散点紧密 _ 布局

这里我们将学习如何在散点图中使用 tight_layout() 方法。

举例:

**# Import Library**

import matplotlib.pyplot as plt

**# Create figure**

fig = plt.figure(1)

**# Define Data**

x =  [1, 2, 3, 4, 5]
y1 = [5, 10, 15, 20, 25]
y2 = [10, 20, 30, 40, 50]

**# Plot**

plt.scatter(x, y1, label='X*5')
plt.scatter(x, y2, label='X*10')

**# Add legend**

plt.legend(loc='center left', bbox_to_anchor=(0.8,-0.1))

**# tight_layout with rect**

plt.tight_layout(rect=(1.5, 0.86, 3.23, 2.55))

**# display**

plt.show()
  • 这里我们使用 scatter() 方法绘制散点图。为了给情节添加一个图例,我们使用 plt.legend() 方法。
  • 我们看到,在不使用 tight_layout() 方法的情况下,散点图的图例和 x 轴标记标签相互重叠。因此,为了避免重叠,我们使用带有 rect 参数的 tight_layout() 方法。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

“Overlapped Scatter Plot”

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.tight_layout()

读取 Matplotlib 虚线

Matplotlib 3d plot tight layout

我们将学习如何使用 tight_layout() 方法自动调整 3d 绘图。

举例:

**# Importing Libraries**

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

**# Create 1st subplot**

fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')

**# Define Data**

x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
z1= [2, 6, 7, 9, 10]

**# Plot graph**

ax.scatter3D(x1, y1, z1, color='m')
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
ax.set_zlabel('Z-Axis')

**# Create 2nd subplot**

ax = fig.add_subplot(1, 2, 2, projection='3d')

**# Define Data**

x2 = np.arange(0, 20, 0.2)
y2 = np.sin(x2)
z2 = np.cos(x2)

**# Plot graph**

ax.scatter3D(x2, y2, z2, color='r')
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
ax.set_zlabel('Z-Axis')

**# auto adjust** 
plt.tight_layout()

**# Display graph**

plt.show()
  • 在上面的例子中,我们导入了 matplotlib.pyplotnumpymplot3d 库。
  • 通过使用 add_subplot() 方法,我们创建第一个子图,然后我们定义用于绘图的数据。
  • ax.scatter3D() 方法用于创建 3D 散点图。
  • 之后,我们再次使用 add_subplot() 方法创建第二个子绘图,然后我们定义用于绘图的数据。
  • 同样,我们使用 ax.scatter3D() 方法绘制另一个 3D 散点图。
  • 为了自动调整绘图布局,我们使用 tight_layout()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout()

读取 Matplotlib plot_date

Matplotlib undo tight_layout

有时,默认情况下,自动调整功能是打开的,以便在每次重新绘制图形时执行调整。如果想关闭它,可以调用 fig.set_tight_layout() 方法,并将 False bool 值传递给该方法。

让我们来看一个例子

**# Import Library**

import numpy as np 
import matplotlib.pyplot as plt 

**# Create figure and subplot**

fig, ax = plt.subplots(1, 2) 

**# Define  Data**

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

**# PLot Subplot 1**

ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

**# Add legend**

ax[0].legend(loc='upper left')

**# Define Data**

y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

**# plot subplot 2**

ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

**# Add legend**

ax[1].legend(loc='upper right')

**# Show**

plt.show() 
  • 在上面的例子中,我们通过使用 matplotlib.pyplot 的 subplots() 方法创建图形和 subplots。
  • 之后,我们使用 arange()sinexp() 方法定义数据。
  • 然后,我们使用 plot() 方法来绘制图形,我们还使用 legend() 函数来定义图例。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

“Auto Adjusted Plot”

从上面生成的输出中,我们得出结论,默认情况下,生成的支线剧情是自动调整的。

Code:撤销或关闭 tight_layout()

**# Import Library** 
import numpy as np 
import matplotlib.pyplot as plt 

**# Create figure and subplot** 
fig, ax = plt.subplots(1, 2) 

**# undo tight_layout**

fig.set_tight_layout(False)

**# Define  Data**

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

**# PLot Subplot 1** 
ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

**# Add legend**

ax[0].legend(loc='upper left')

**# Define Data** 
y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

**# plot subplot 2** 
ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

**# Add legend**

ax[1].legend(loc='upper right')

**# Show**

plt.show() 

现在通过使用上面的代码,我们可以撤销支线剧情的自动调整。这里我们用 False 值调用 fig.set_tight_layout() 方法,并撤销绘图的自动布局特性。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

fig.set_tight_layout(False)

读取 Matplotlib 日志日志图

Matplotli b 紧 _ 布局备选

紧 _ 布局 的替代方案是 约束 _ 布局

我们使用 constrained_layout 在您的图形中清晰地拟合图形。*constrained _ layout*自动调整支线剧情、图例、彩条、标题和标签,使其适合人物区域,同时仍保留用户要求的布局。

在向图形添加任何轴之前,必须激活 constrained_layout 。我们可以用两种方式激活它。

  • 通过 rcParams 激活:
matplotlib.pyplot.rcParams['figure.constrained_layout.use']=True
  • 通过参数激活 subplots()或 figure()方法:
**# Using subplots()** 
plt.subplots(constrained_layout=True)

**# Uisng figure()** 
plt.figure(constrained_layout=True)

我们先来看一个简单的例子,以便更清楚地理解:

**# Importing library**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplots** 
fig, ax = plt.subplots(2,2, figsize=(8, 5))

**# Define Data**

x1= np.random.randint(10,size=500)

x2= np.linspace(100, 200, num=10)
y2= np.cos(x2)

x3= np.arange(0.0, 30.0 , 0.02) 
y3= np.tan(x3)

x4 = np.arange(0.0, 30.0 , 0.02) 
y4 = np.sin(x4)

**# Plot lines**

ax[0, 0].plot(x1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

**# Add xlabel**

ax[0, 0].set_xlabel('X-Axis')
ax[1, 0].set_xlabel('X-Axis')
ax[0, 1].set_xlabel('X-Axis')
ax[1, 1].set_xlabel('X-Axis')

**# Add ylabel**

ax[0, 0].set_ylabel('Y-Axis')
ax[1, 0].set_ylabel('Y-Axis')
ax[0, 1].set_ylabel('Y-Axis')
ax[1, 1].set_ylabel('Y-Axis')

**# Display**

plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  • 在上面的例子中,轴标签或标题或刻度标签相互重叠,使绘图混乱。为了防止这种情况,需要调整轴的位置。
  • 对于支线剧情,这可以通过使用 Figure.subplots_adjust 调整参数来手动完成,或者我们将通过指定 constrained_layout=True 来自动完成调整。

代码:用于自动调整

**# Importing library**

import numpy as np
import matplotlib.pyplot as plt

**# Create figure and subplots**

fig, ax = plt.subplots(2,2, figsize=(8, 5), constrained_layout=True)

**# Define Data**

x1= np.random.randint(10,size=500)

x2= np.linspace(100, 200, num=10)
y2= np.cos(x2)

x3= np.arange(0.0, 30.0 , 0.02) 
y3= np.tan(x3)

x4 = np.arange(0.0, 30.0 , 0.02) 
y4 = np.sin(x4)

**# Plot lines**

ax[0, 0].plot(x1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

**# Add xlabel**

ax[0, 0].set_xlabel('X-Axis')
ax[1, 0].set_xlabel('X-Axis')
ax[0, 1].set_xlabel('X-Axis')
ax[1, 1].set_xlabel('X-Axis')

**# Add ylabel**

ax[0, 0].set_ylabel('Y-Axis')
ax[1, 0].set_ylabel('Y-Axis')
ax[0, 1].set_ylabel('Y-Axis')
ax[1, 1].set_ylabel('Y-Axis')

**# Display**

plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

constrained_layout=True

读取Matplotlib subplots _ adjust

Matplotlib constrained _ layout vs tight _ layout

我们将讨论 constrained_layout 和 tight_layout。

| 约束 _ 布局 | 紧 _ 布局 |
| 它保留用户请求的逻辑布局。 | 它可能不会保留用户请求的逻辑布局。 |
| constrained_layout 使用约束解算器来确定轴的大小。 | tight_layout 不使用约束求解器来确定轴的大小。 |
| 在添加任何轴之前,需要激活 constrained_layout。 | 添加轴之前,不需要激活 tight_layout。 |
| 通过 RC params:
PLT . RC params[’ figure . constrained _ layout . use ‘]= True 激活 | 通过 RC params:
PLT . RC params[’ figure . autolayout ']= True 激活 |
| 通过方法激活:
PLT . subplots(constrained _ layout = True) | 通过方法激活:
plt.tight_layout() |

constrained_layout vs tight_layout

我们来看一个例子:

示例:tight_layout

**# Import Library** 
from matplotlib.figure import Figure

**# Create figure** 
fg = Figure()

**# Create subplot** 
ax = fg.subplots(5, 1)

**# Plot** 
for i in range(5):
    ax[i].plot(range(25+25*i))

**# Add title** 
fg.suptitle('lots of lines')

**# tight_layout**

fig.tight_layout()

**# Save image** 
fg.savefig("tight_layout.png")

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

tight_layout

示例:constrained_layout

**# Import Library**

from matplotlib.figure import Figure

**# Create figure** 
fg = Figure(constrained_layout=True)

**# Create subplot**

ax = fg.subplots(5, 1)

**# Plot**

for i in range(5):
    ax[i].plot(range(25+25*i))

**# Add title**

fg.suptitle('lots of lines')

**# Save image**

fg.savefig("constrained_layout.png")

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

constrained_layout

从上面的例子中,我们看到 tight_layout 并没有更好的工作。为了让带有支线剧情和标签的图形更好地工作,使用 constrained_layout

您可能还喜欢:

因此,在这个 Python 教程中,我们已经讨论了 "Matplotlib tight_layout" ,并且我们还涵盖了一些与之相关的例子。这些是我们在本教程中讨论过的以下主题。

  • Matplotlib tick_layout
  • Matplotlib tight_layout 示例
  • Matplotlib 紧密布局焊盘
  • Matplotlib 紧密布局 hspace
  • Matplotlib 紧密布局 wspace
  • Matplotlib 紧密布局矩形
  • Matplotlib tight_layout 保存图
  • Matplotlib tight_layout 子情节
  • Matplotlib tight_layout suptitle
  • Matplotlib tight_layout 剪切标签
  • Matplotlib 紧密布局图例
  • Matplotlib 紧密布局 bbox
  • Matplotlib tight_layout 未应用
  • Matplotlib tight_layout rcparams
  • Matplotlib imshow tight_layout
  • Matplotlib tight_layout gridspec
  • Matplotlib tight_layout 颜色条
  • Matplotlib 表格紧密布局
  • Matplotlib 散点图紧密布局
  • Matplotlib 3d plot tight layout
  • Matplotlib undo tight_layout
  • Matplotlib 紧密布局替代方案
  • Matplotlib constrained_layout 与 tight_layout

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传Bijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/*

Matplotlib 时间序列图

原文:https://pythonguides.com/matplotlib-time-series-plot/

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

在本 Python Matplotlib 教程中,我们将讨论 Matplotlib 时序图。在这里,我们将使用 matplotlib 涵盖与时间序列图相关的不同示例。我们还将讨论以下主题:

  • Matplotlib 时间序列
  • Matplotlib 时间序列情节熊猫
  • Matplotlib 时间序列散点图
  • Matplotlib 多时间序列图
  • Matplotlib 时间序列条形图
  • Matplotlib 绘制时间序列 x 轴
  • Python 时间序列图 seaborn
  • Matplotlib 箱线图时间序列
  • Python 时间序列交互式绘图
  • Matplotlib 时间序列多条形图
  • Matplotlib 绘制有间隙的时间序列

目录

Matplotlib 时间序列

这里先来了解一下什么是时序 plot,讨论一下为什么在 matplotlib 中需要它。

什么是时间序列图:

时间序列数据是在一段时间内收集的数据点的集合,具有时间索引。这些观测是在整个时间内以均匀的间隔进行的。数据可视化在绘制时间序列图中起着重要的作用。

我们需要时间序列图的地方:

ECG 信号、EEG 信号、股票市场数据、天气数据等等都是时间索引的,并且在一段时间内被记录。分析这些数据和预测未来观测的研究领域要广泛得多。

另外,检查: Matplotlib 更新循环中的绘图

Matplotlib 时间序列剧情熊猫

在这里,我们学习绘制将在熊猫中创建的时间序列图。所以首先,我们必须在熊猫身上创建一个样本数据集。

下面是 在 Pandas 中创建 DataFrame 的语法:

pandas.DataFrame(data, index, columns, dtype, copy)

让我们看看创建数据帧的源代码:

**# Import Library**

import pandas as pd

**# Defne Data** 
timeseries_data = { 
    'Date': ['2021-12-26', '2021-12-29',
             '2021-12-27', '2021-12-30',
             '2021-12-28', '2021-12-31' ], 

    'Washington': [42, 41, 41, 42, 42, 40],

    'Canada' : [30, 30, 31, 30, 30, 30],

    'California' : [51, 50, 50, 50, 50, 50]
}

**# Create dataframe**

dataframe = pd.DataFrame(timeseries_data,columns=['Date', 'Washington', 'Canada', 'California'])

**# Changing the datatype**

dataframe["Date"] = dataframe["Date"].astype("datetime64")

**# Setting the Date as index**

dataframe = dataframe.set_index("Date")
dataframe

输出:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Data Set

绘制数据的源代码:

**# Import Library** 
import matplotlib.pyplot as plt

**# Plot**

plt.plot(dataframe["Canada"], marker='o')

**# Labelling** 

plt.xlabel("Date")
plt.ylabel("Temp in Faherenheit")
plt.title("Pandas Time Series Plot")

**# Display**

plt.show()
  • 首先导入 matplotlib.pyplot 库。
  • 接下来,为加拿大列绘制图表。
  • 为了在轴上添加标签,我们使用了 xlabel()ylabel() 函数。
  • 为了添加标题,我们使用了 title() 函数。

输出:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Pandas Time Series Plot

另外,请阅读:Matplotlib fill _ between–完整指南

Matplotlib 时间序列散点图

现在我们学习使用 Matplotlib 中的散点图绘制时序图。

举例:

在这个例子中,我们把上面创建的 DataFrame 作为一个数据。

**# Import Library** 
import matplotlib.pyplot as plt

**# Plot scatter**

plt.scatter(dataframe.index, dataframe["Washington"])

**# Labelling** 

plt.xlabel("Date")
plt.ylabel("Temp in Faherenheit")

**# Auto space**

plt.tight_layout()

**# Display** 
plt.show()

这里我们画了一个散点图,表示日期温度**。**

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Scatter Plot

阅读:Matplotlib plot _ date–完整教程

Matplotlib 多个时间序列图

在这里,我们将学习使用 matplotlib 在一个图中绘制多个时间序列。

举例:

**# Import Libraries**

import matplotlib.pyplot as plt
import datetime
import numpy as np
import pandas as pd

**# Create figure** 
fig = plt.figure(figsize=(12, 8))

**# Define Data** 
df1 = pd.DataFrame({'date': np.array([datetime.datetime(2021, 
                    12, i+1) for i in range(20)]),
                   'blogs_read': [4, 6, 5, 8, 15, 13, 18, 6, 5, 
                  3, 15, 14, 19, 21, 15, 19, 25, 24, 16, 26]})

df2 = pd.DataFrame({'date': np.array([datetime.datetime(2021, 
                     12, i+1)
 for i in range(20)]),
                   'blogs_unread': [1, 1, 2, 3, 3, 3, 4, 3, 2,     
                    3, 4, 7, 5, 3, 2, 4, 3, 6, 1, 2]})

**# Plot time series**

plt.plot(df1.date, df1.blogs_read, label='blogs_read', 
         linewidth=3)
plt.plot(df2.date, df2.blogs_unread, color='red', 
         label='blogs_unread', linewidth=3)

**# Add title and labels** 
plt.title('Blogs by Date')
plt.xlabel('Date')
plt.ylabel('Blogs')

**# Add legend**

plt.legend()

**# Auto space** 
plt.tight_layout()

**# Display plot** 
plt.show() 
  • 首先导入必要的库,如 matplotlib.pyplotdatetimenumpypandas
  • 接下来,要增加图形的大小,使用 figsize() 函数。
  • 为了定义数据坐标,我们创建 pandas DataFrame
  • 为了绘制时间序列,我们使用 plot() 函数。
  • 要给绘图添加标题,使用 title() 函数。
  • 为了在轴上添加标签,我们使用了 xlabel()ylabel() 函数。
  • 要添加图例,使用 legend() 函数。
  • 要显示绘图,使用 show() 功能。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Multiple Time Series

阅读: Matplotlib 旋转刻度标签

Matplotlib 时间序列条形图

这里我们将学习使用 Matplotlib 中的条形图绘制时间序列。

点击此处下载数据:

Sales.CSV

举例:

**# Import Library** 
import pandas as pd 
import matplotlib.pyplot as plt 

**# Read csv** 
data= pd.read_csv('Sales.csv')

**# Convert data frame** 
df=pd.DataFrame(data)

**# Initilaize list** 
X = list(df.iloc[:,0])
Y = list(df.iloc[:,1])

**# Set figure** 
plt.figure(figsize=(15, 12))

**# Bar Plot** 
plt.bar(X, Y)

**# Setting Ticks** 
plt.tick_params(axis='x',labelsize=15,rotation=90)
plt.tight_layout()

**# Display**

plt.show() 
  • 首先,我们导入必要的库,如 matplotlib.pyplotpandas
  • 接下来,读取 CSV 文件。
  • 之后,从 CSV 文件创建 DataFrame。
  • 初始化 X 和 y 的列表。
  • 为了绘制条形图,我们使用了 bar() 函数。
  • 要更改 tick 设置,我们使用 tick_params() 函数。
  • 为了设置空间,我们使用 tight_layout() 函数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.bar()

读取: Matplotlib x 轴标签

Matplotlib 绘制时间序列 x 轴

这里我们将学习在 Matplotlib 中设置时间序列数据图的 x 轴。

我们来看一个例子:

**# Import Library** 
import matplotlib.pyplot as plt
from datetime import datetime, timedelta

**# Define data** 
dates = [
    datetime(2021, 9, 21),
    datetime(2021, 9, 22),
    datetime(2021, 9, 23),
    datetime(2021, 9, 24),
    datetime(2021, 9, 25),
    datetime(2021, 9, 26),
    datetime(2021, 9, 27),
]

y = [0, 1.8, 2, 3.5, 4, 5.6, 6]

**# Plot** 
plt.plot_date(dates, y)

**# Setting axes** 
plt.tight_layout()
plt.tick_params(axis='x', rotation=90)

**# Display**

plt.show()
  • 导入库 matplotlib.pyplotdatetime
  • 定义数据轴 x 和 y。
  • 为了绘制日期,我们使用 plot_date() 函数。
  • 为了设置分笔成交点的设置,我们使用了 tick_params() 函数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.plot_date()

阅读: Matplotlib 多条形图

Python 时间序列图 seaborn

在这里,我们将学习如何用 seaborn 创建一个时间序列图。

Seaborn 是一个优秀的 Python 可视化工具,用于绘制统计图像。它包括吸引人的默认样式和调色板,使统计图表更有吸引力。它基于最新版本的 matplotlib 包,并与 pandas 的数据结构紧密集成。

点击 上的 下载数据集销售。CSV 文件:

Sales.CSV

我们来看一个例子:

**# Import Library** 
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt 

**# Read csv** 
data= pd.read_csv('Sales.csv')

**# Convert to dataframe** 
df=pd.DataFrame(data)

**# Initilaize list** 
X = list(df.iloc[:,0])
Y = list(df.iloc[:,1])

**# Set figure** 
plt.figure(figsize=(12,10))

**# Seaborn**

sns.lineplot(x=X, y=Y)

**# Setting Ticks** 
plt.tick_params(axis='x',labelsize=15,rotation=90)
plt.tight_layout()

**# Display** 
plt.show() 
  • 首先导入 matplotlib.pyplot熊猫seaborn 库。
  • 接下来,使用 read_csv() 函数读取 CSV 文件。
  • 要将数据转换成数据帧,使用 pandas 的 DataFrame() 函数。
  • 为了初始化列表,我们使用 pandas 的 iloc() 函数。
  • 要设置图的尺寸,使用 figsize() 图的方法。
  • 为了用 seaborn 库创建时间序列图,我们使用了 lineplot() 方法。
  • 要更改 ticks 的设置,我们使用 tick_params() 函数。
  • 要设置绘图的调整,使用 tight_layout() 功能。
  • 要显示绘图,使用 show() 功能。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

sns.lineplot()

阅读: Matplotlib 3D 散点图

Matplotlib 箱线图时间序列

在这里,我们将学习使用 Matplotlib 使用 seaborn boxplot 绘制时间序列图。

举例:

**# Import libraries**

import numpy as np
import pandas as pd
import seaborn
import matplotlib.pyplot as plt

**# Define Data** 
data = pd.DataFrame(np.random.randn(100), 
                    index=pd.date_range(start="2021-12-01", 
                    periods=100, freq="H"))
data.groupby(lambda x: x.strftime("%Y-%m-
            %d")).boxplot(subplots=False, figsize=(12,9))

**# Display** 
plt.show()
  • 导入 numpy熊猫seabornmatplotlib.pyplot 库。
  • 使用 DataFrame() 函数创建熊猫数据框。
  • 要定义用于绘图的数据,使用 random.randn() 函数并将索引设置为日期。
  • 要按日期绘制分组,请使用 groupby() 函数。
  • 要创建箱线图,使用 boxplot() 函数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

boxplot()

读取:水平线 matplotlib

Python 时间序列交互图

Plotly 是一个 Python 开源数据可视化模块,支持各种图形,如折线图、散点图、条形图、直方图和面积图。Plotly 是一个绘图工具,使用 javascript 创建交互式图形。

使用下面提到的命令进行 Plotly 安装:

pip install plotly

点击 上的 下载数据集销售。CSV 文件:

Sales.CSV

我们来看一个例子:

**# Import Library**

import pandas as pd
import plotly.express as px 
import matplotlib.pyplot as plt 

**# Read csv**

data= pd.read_csv('Sales.csv')

**# Convert data frame**

df=pd.DataFrame(data)

**# Initilaize list** 

X = list(df.iloc[:,0])
Y = list(df.iloc[:,1])

**# Set figure**

plt.figure(figsize=(12,10))

**# Plotly graph**

plot = px.line(x=X, y=Y)

**# Setting Ticks** 
plt.tick_params(axis='x',labelsize=15,rotation=90)
plt.tight_layout()

**# Display** 
plot.show() 
  • 导入熊猫plotly.expressmatplotlib.pyplot 等必要的库。
  • 读取 CSV 文件,使用 read_csv() 函数。
  • 使用 DataFrame() 函数将 CSV 文件转换为数据帧。
  • 为了初始化列表,我们使用 iloc() 函数。
  • 要绘制交互式时间序列折线图,使用 plotly.express 模块的 line() 函数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Interactive Time Series Plot

读取: Matplotlib 反转 y 轴

Matplotlib 时间序列多条线图

在本节中,我们将学习使用多个条形图绘制时间序列图。我们在这里绘制了显示特定时期出生人数的图表。

我们来看一个例子:

**# Import Libraries**

import pandas as pd
import matplotlib.pyplot as plt

**# Creating dataframe** 
df = pd.DataFrame({
     'Dates':['2021-06-10', '2021-06-11',
             '2021-06-12', '2021-06-13',
             '2021-06-14', '2021-06-15'],
    'Female': [200, 350, 150, 600, 500, 350],
    'Male': [450, 400, 800, 250, 500, 900]
})

**# Plotting graph** 
df.plot(x="Dates", y=["Female", "Male"], kind="bar")

**# Show**

plt.show()

说明:

  • 导入 matplotlib 库进行数据可视化。
  • 接下来,导入 pandas 库来创建数据帧。
  • 然后使用 DataFrame() 函数在 pandas 中创建数据帧。
  • 为了创建一个多条形图,我们使用了 plot() 方法,并将它的种类定义为条形图
  • 为了可视化这个图,我们使用了 show() 函数。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

df.plot(kind=’bar’)

阅读:将图例放在绘图 matplotlib 之外

Matplotlib 绘制带有间隙的时间序列

在本节中,我们将学习如何使用 matplotlib 绘制带有间隙的时间序列。首先,让我们来看一下 gap 是什么意思:

假设我们有一个 CSV 格式的数据集,其中有一些缺少值。然后,这些空白值或空白单元格被替换为 NaN 值。因此,当我们可视化这种数据集时,我们得到的是一个带有断点而不是连续线条的图表。

要下载数据集,请单击最高温度美国城市:

Max Temp USA Cities

为了更清楚地理解概念,我们来看不同的例子:

  • 首先,我们导入了必要的库,如 pandasmatplotlib.pyplot
  • 在这之后,使用熊猫的 read_csv() 函数读取 csv 文件。
  • 要查看数据集,请将其打印出来。

源代码:

**# Import Libraries**

import pandas as pd 
import matplotlib.pyplot as plt 

**# Read** `CSV`

data= pd.read_csv('Max Temp USA Cities.csv')

**# Print** 

data

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

data

  • 接下来,我们使用 DataFrame() 函数将 CSV 文件转换为熊猫的数据帧。
  • 如果你想查看数据框,打印出来。

源代码:

**# Convert data frame** 
df=pd.DataFrame(data)

**# Print**

df

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

df

  • 使用 iloc() 函数初始化列表,从 pandas 数据帧中按位置选择行和列。

源代码:

**# Initilaize list** 
dates = list(df.iloc[:,0])
city_1 = list(df.iloc[:,1])
city_2 = list(df.iloc[:,2])
city_3 = list(df.iloc[:,3])
city_4 = list(df.iloc[:,4])
  • 现在,使用 figsize() 函数设置图形大小。
  • 要设置 x 轴的旋转和标签尺寸,使用 tick_params() 函数。
  • 要在 x 轴上设置标签,使用 xlabel() 函数。
  • 要在 y 轴上设置标签,使用 ylabel() 函数。

源代码:

**# Set Figure** `Size`

plt.figure(figsize=(8,6))

**# Setting Ticks**

plt.tick_params(axis='x',labelsize=10,rotation=90)

**# Labels** 
plt.xlabel("Dates")
plt.ylabel("Temp")
  • 要绘制没有间隙的折线图,请使用 plot() 函数,并向其传递没有缺失值的数据坐标。
  • 要设置标记,请将标记作为参数传递。
  • 为了可视化图表,使用 show() 函数。

示例#1(无间隙)

**# Plot**

plt.plot(dates, city_4, marker='o')

**# Display** 
plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Without Gaps

示例#2(有间隙)

**# Set figure**

plt.figure(figsize=(8,6))

**# Plot**

plt.plot(dates,city_1, marker='o')

**# Labels**

plt.xlabel("Dates")
plt.ylabel("Temp")

**# Setting Ticks**

plt.tick_params(axis='x',labelsize=10,rotation=90)

**# Display**

plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

With Gaps

示例#3(有间隙)

这里我们绘制了日期和洛杉矶市之间的图表。

**# Set figure**

plt.figure(figsize=(8,6))

**# Plot**

plt.plot(dates,city_2, marker='o')

**# Labels**

plt.xlabel("Dates")
plt.ylabel("Temp")

**# Setting Ticks**

plt.tick_params(axis='x',labelsize=10,rotation=90)

**# Display**

plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.plot()

示例#4(有间隙)

这里我们绘制了日期和费城之间的图表。

**# Set figure**

plt.figure(figsize=(8,6))

**# Plot**

plt.plot(dates,city_3, marker='o')

**# Labels**

plt.xlabel("Dates")
plt.ylabel("Temp")

**# Setting Ticks** 
plt.tick_params(axis='x',labelsize=10,rotation=90)

**# Display** 
plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

plt.plot()

示例#5(在一个图中有或没有间隙)

**# Set figure**

plt.figure(figsize=(8,6))

**# Plot**

plt.plot(dates,city_1, marker='o')
plt.plot(dates,city_4, marker='o')

**# Labels**

plt.xlabel("Dates")
plt.ylabel("Temp")

**# Setting Ticks**

plt.tick_params(axis='x',labelsize=10,rotation=90)

**# Display**

plt.show()

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

With or Without Gaps

你可能也喜欢阅读下面的 Matplotlib 教程。

在本 Python 教程中,我们已经讨论了“ Matplotlib 时间序列图”,并且我们还介绍了一些与之相关的示例。这些是我们在本教程中讨论过的以下主题。

  • Matplotlib 时间序列
  • Matplotlib 时间序列情节熊猫
  • Matplotlib 时间序列散点图
  • Matplotlib 多时间序列图
  • Matplotlib 时间序列条形图
  • Matplotlib 绘制时间序列 x 轴
  • Python 时间序列图 seaborn
  • Matplotlib 箱线图时间序列
  • Python 时间序列交互式绘图
  • Matplotlib 时间序列多条形图
  • Matplotlib 绘制有间隙的时间序列

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传Bijay Kumar

Python 是美国最流行的语言之一。我从事 Python 工作已经有很长时间了,我在与 Tkinter、Pandas、NumPy、Turtle、Django、Matplotlib、Tensorflow、Scipy、Scikit-Learn 等各种库合作方面拥有专业知识。我有与美国、加拿大、英国、澳大利亚、新西兰等国家的各种客户合作的经验。查看我的个人资料。

enjoysharepoint.com/

【源码免费下载链接】:https://renmaiwang.cn/s/2gdnj 《R语言数据挖掘方法及应用》由薛薇编写而成的一本系统阐述R语言在数据挖掘领域前沿技术的著作。该书旨在指导读者学会使用R语言进行高效、实用的数据分析与建模工作,涵盖了从理论基础到实践操作的全过程。作为一款功能强大且开源的统计计算和图形处理平台,R语言凭借其丰富的工具库和社区支持,在数据分析与可视化方面展现出显著优势。在数据挖掘领域,R语言提供了包括`caret`、`randomForest`、`tm`、`e1071`等广泛使用的专用包,这些工具能够帮助用户更便捷地进行数据预处理、特征选择、模型构建和结果评估。全书首先介绍R语言的基本知识体系,涵盖环境配置与安装方法、基础语法规范以及常见数据类型分析等内容。这些基础知识是开展后续数据分析工作的必备技能,通过学习可以快速掌握R语言的核心功能。随后章节深入讲解了数据挖掘的主要概念与流程,包括数据清洗、转换整理和探索性分析等环节,同时详细阐述了分类、聚类、关联规则挖掘及预测等多种典型任务的具体实施方法。这些内容有助于读者全面理解数据挖掘的整体架构及其核心工作步骤。在应用实践部分,薛薇老师结合真实案例展示了R语言在实际业务场景中的具体运用,例如市场细分分析、客户流失预测以及个性化推荐系统等。通过这些案例研究,读者可以深入学习如何利用相关工具包解决实际问题,并提升数据分析能力。此外,书中配套的“案例数据集”和“代码资源”为读者提供了实践操作的机会,使理论知识能够更好地转化为动手技能。通过实际操作分析,读者可以加深对R语言数据挖掘方法的理解并灵活运用。总之,《R语言数据挖掘方法及应用》是一部全面讲解R语言在数据分析与建模领域的教材,无论你是刚开始学习的新人还是经验丰富的专业人士,都能从中获益匪浅。通过深入研读此书,你可以掌握R语言的数据挖掘技巧,并将其应用到实
内容概要:本文提出了一种基于改进粒子滤波算法的无人机三维航迹预测方法,并通过Matlab代码实现仿真验证。该方法针对传统粒子滤波在无人机轨迹预测中存在的粒子退化和计算复杂度高等问题,引入优化策略提升滤波精度与效率,有效提高了对无人机运动轨迹的非线性、非高斯环境下的预测能力。文中详细阐述了算法原理、模型构建流程及关键步骤,包括状态转移建模、观测方程设计、重采样优化等,并结合三维空间中的实际飞行轨迹进行仿真实验,验证了所提方法相较于标准粒子滤波在位置预测误差和收敛速度方面的优越性。; 适合人群:具备一定信号处理、导航估计算法基础,熟悉Matlab编程,从事无人系统、智能交通、航空航天等相关领域研究的研究生或科研人员; 使用场景及目标:①应用于无人机实时轨迹预测与状态估计系统中,提升飞行安全性与自主性;②为复杂环境下非线性动态系统的建模与滤波算法研究提供技术参考;③【预测】改进粒子滤波的无人机三维航迹预测方法(Matlab代码实现)支持后续扩展至多无人机协同跟踪与避障系统的设计与仿真; 阅读建议:建议结合Matlab代码逐模块分析算法实现细节,重点关注粒子滤波的改进机制与三维可视化结果对比,同时可尝试替换不同运动模型或噪声条件以深入理解算法鲁棒性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值