Matplotlib sharex 参数
本次会议将讨论 subplot()
函数和共享轴。我们还将解释如何使用 sharex
参数 Matplotlib 从多个子图中共享轴。
Matplotlib 中的 subplot()
函数
subplot()
函数表示单个图中的多个图,我们在同一图中绘制图。这就是为什么我们可以在一个图中有多个图。
这个 subplot()
函数采用这三个参数。第一个代表行,第二个代表列,第三个参数代表索引。
语法:
subplot(r,c,i)
r
表示行。c
参数表示一列,i
参数是绘图的索引。使用这些参数将帮助你指定绘图单元,我们可以按降序调整绘图位置。
使用 sharex
参数从多个子图中共享轴
我们将定义我们的绘图,与哪个轴共享轴无关紧要,但如果我们以"311"
顺序定义 subplot
是有意义的。我们有一个轴来共享 x 轴,因此 sharex
将等于你可以与定义的子图共享。
将轴限制更改为一个轴将自动显示在另一个轴上,反之亦然。当你浏览工具栏时,这些轴将在其共享轴中通过工具栏。
现在,让我们编写代码并快速查看解释。首先,我们需要导入所需的库。
import matplotlib.pyplot as plt
import numpy as np
为 x
和 y
值创建数据,然后我们为 "311"
绘制子图,其中 "3"
是一行,"1"
是一列。 "1"
是一个索引。
tick_params()
方法将刻度设置到给定的轴。在我们的例子中,我们只是为 x 轴设置它。
axis1 = plt.subplot(311)
plt.plot(range_samples, sine)
plt.tick_params('x', labelsize=6)
在这个 subplot()
方法中,我们将 axis1
传递给 sharex
参数。axis1
是存储第一个子图的变量,这意味着我们希望与第一个子图共享第二个子图的 x 轴。
axis2 = plt.subplot(312, sharex=axis1)
我们创建了第三个带有共享 x
和 y
轴的子图,并且该子图还与第一个子图共享其轴。xlim()
方法设置 x 轴值的限制,这就像我们可以传递它的范围。
axis3 = plt.subplot(313, sharex=axis1, sharex=axis1)
plt.plot(range_samples, sine2)
plt.xlim(0.01, 5.0)
完整源代码:
import matplotlib.pyplot as plt
import numpy as np
range_samples = np.arange(0.01, 5.0, 0.01)
sine = np.sin(2 * np.pi * range_samples)
inverse = np.exp(-range_samples)
sine2= np.sin(4 * np.pi * range_samples)
axis1 = plt.subplot(311)
plt.plot(range_samples, sine)
plt.tick_params('x', labelsize=6)
# This line only share x
axis2 = plt.subplot(312, sharex=axis1)
plt.plot(range_samples, inverse)
# make these tick labels invisible
plt.tick_params('x', labelbottom=False)
# This lin share x and y axes
axis3 = plt.subplot(313, sharex=axis1, sharey=axis1)
plt.plot(range_samples, sine2)
plt.xlim(0.01, 5.0)
plt.show()
输出:
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串