python - 如何为子图设置公共(public)轴标签

我有以下情节:

import matplotlib.pyplot as plt

fig2 = plt.figure()
ax3 = fig2.add_subplot(2,1,1)
ax4 = fig2.add_subplot(2,1,2)
ax4.loglog(x1, y1)
ax3.loglog(x2, y2)
ax3.set_ylabel('hello')

我希望能够不仅为两个子图中的每一个创建轴标签和标题,而且还可以为跨越两个子图的通用标签创建。例如,由于两个图具有相同的轴,因此我只需要一组 x 轴和 y 轴标签。不过,我确实希望每个子图都有不同的标题。

我尝试了一些方法,但没有一个能正常工作

最佳答案

您可以创建一个覆盖两个子图的大子图,然后设置公共(public)标签。

import random
import matplotlib.pyplot as plt

x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]

fig = plt.figure()
ax = fig.add_subplot(111)    # The big subplot
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top=False, bottom=False, left=False, right=False)

ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Set common labels
ax.set_xlabel('common xlabel')
ax.set_ylabel('common ylabel')

ax1.set_title('ax1 title')
ax2.set_title('ax2 title')

plt.savefig('common_labels.png', dpi=300)

另一种方法是使用 fig.text() 直接设置常用标签的位置。

import random
import matplotlib.pyplot as plt

x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Set common labels
fig.text(0.5, 0.04, 'common xlabel', ha='center', va='center')
fig.text(0.06, 0.5, 'common ylabel', ha='center', va='center', rotation='vertical')

ax1.set_title('ax1 title')
ax2.set_title('ax2 title')

plt.savefig('common_labels_text.png', dpi=300)

https://stackoverflow.com/questions/6963035/

相关文章:

python - 如何从生成器构建 numpy 数组?

python - 我如何告诉 matplotlib 我完成了一个情节?

python - 删除字符串的第一个字符

python - 在python中调用带有参数列表的函数

python - 如何使用 Python 登录网页并检索 cookie 以供以后使用?

linux - tar:添加当前目录中的所有文件和目录,包括 .svn 等

linux - Bash 中的多线程

python - 如何中止 Python 脚本的执行?

linux - WGET 是否超时?

linux - grep 不作为正则表达式