matplotlib共享坐标轴的实现(X或Y坐标轴)

要实现matplotlib共享坐标轴,可以使用fig.add_subplot() 和 plt.subplots() 函数,这两个函数都支持共享坐标轴。

要实现matplotlib共享坐标轴,可以使用fig.add_subplot() 和 plt.subplots() 函数,这两个函数都支持共享坐标轴。

共享x轴的实现:
我们可以声明一个figure,然后使用add_subplot()函数添加需要的子图,同时指定sharex参数用来共享x轴。代码如下:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,6))
ax1 = fig.add_subplot(2,1,1) # 创建第一个子图
ax2 = fig.add_subplot(2,1,2, sharex=ax1) # 创建第二个子图,并共享ax1的x轴

# 绘制数据
ax1.plot([1,2,3], [4,5,6])
ax2.plot([4,5,6], [7,8,9])

# 添加标签和标题
ax1.set_xlabel('X轴')
ax1.set_ylabel('Y轴')
ax2.set_xlabel('X轴')
ax2.set_ylabel('Y轴')
plt.suptitle('共享x轴的子图', fontsize=16)

# 显示图像
plt.show()

本示例中,使用fig.add_subplot()函数创建了两个子图,并且将第二个子图的sharex参数设置为第一个子图的对象ax1,这样就实现了x轴共享。

共享y轴的实现:
同理,我们可以通过设置add_subplot()函数的sharey参数来实现y轴共享。

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,6))
ax1 = fig.add_subplot(1,2,1) # 创建第一个子图
ax2 = fig.add_subplot(1,2,2, sharey=ax1) # 创建第二个子图,并共享ax1的y轴

# 绘制数据
ax1.plot([1,2,3], [4,5,6])
ax2.plot([4,5,6], [7,8,9])

# 添加标签和标题
ax1.set_xlabel('X轴')
ax1.set_ylabel('Y轴')
ax2.set_xlabel('X轴')
ax2.set_ylabel('Y轴')
plt.suptitle('共享y轴的子图', fontsize=16)

# 显示图像
plt.show()

本示例中,使用fig.add_subplot()函数创建了两个子图,并且将第二个子图的sharey参数设置为第一个子图的对象ax1,这样就实现了y轴共享。

本文标题为:matplotlib共享坐标轴的实现(X或Y坐标轴)

基础教程推荐