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

标签 python matplotlib label subplot axes

我有以下情节:

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)

common_labels.png

另一种方法是使用 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)

common_labels_text.png

关于python - 如何为子图设置公共(public)轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6963035/

相关文章:

python - BeautifulSoup 汉字编码错误

python - 基本的 python vlookup 等价物

c# - 如何在代码隐藏的 asp.net 中使标签闪烁

python - 如何在 Django 中不使用模板返回 JSON?

python - 具有不等组的 Pandas 条形图

python - 结合固定和区域设置表示法进行字符串格式化

python - 使用 pyplot.scatter() 方法绘制元组列表(x 坐标、y 坐标、颜色)

c# - 将来自 webform 的物理标签存储到列表 C#

Python Bokeh 刻度标签

Python 无法更新 JSON 字符串的坐标