在matplotlib中绘制共享x轴的两个图形

10 投票
2 回答
12513 浏览
提问于 2025-04-15 14:12

我需要在一个屏幕上画两个图。x轴是一样的,但y轴要不同。

我该怎么在'matplotlib'中做到这一点呢?

2 个回答

7

subplot 这个功能可以让你在同一个画布上绘制多个图形。你可以查看链接中的文档页面,里面有相关的示例。

在示例目录中,有一个共享坐标轴的绘图示例,文件名叫 shared_axis_demo.py

from pylab import *

t = arange(0.01, 5.0, 0.01)
s1 = sin(2*pi*t)
s2 = exp(-t)
s3 = sin(4*pi*t)
ax1 = subplot(311)
plot(t,s1)
setp( ax1.get_xticklabels(), fontsize=6)

## share x only
ax2 = subplot(312, sharex=ax1)
plot(t, s2)
# make these tick labels invisible
setp( ax2.get_xticklabels(), visible=False)

# share x and y
ax3 = subplot(313,  sharex=ax1, sharey=ax1)
plot(t, s3)
xlim(0.01,5.0)
show() 
19

twinx 是你需要的函数;这里有一个使用它的例子

twinx 示例

撰写回答