Bor*_* L. 23 python matplotlib
我是最近转换为Python的Matlab用户.我自己管理的大多数Python技能,但是通过绘图,我已经碰壁了,需要一些帮助.
这就是我要做的......
我需要制作一个由3个子图组成的图形,其中包含以下属性:
顺便说一下,我知道如何制作所有这些,只是在一个图中.这就是我现在面临的问题.
例如,这是我理想的子图布局:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = s1*s2
fig = plt.figure()
ax1 = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2)
ax2 = plt.subplot2grid((4,3), (2,0), colspan=3)
ax3 = plt.subplot2grid((4,3), (3,0), colspan=3)
ax1.plot(t,s1)
ax2.plot(t[:150],s2[:150])
ax3.plot(t[30:],s3[30:])
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
注意不同子图的x轴是如何未对齐的.我不知道如何在这个图中对齐x轴,但是如果我做这样的事情:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = s1*s2
fig2, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, sharex=True)
ax1.plot(t,s1)
ax2.plot(t[:150],s2[:150])
ax3.plot(t[30:],s3[30:])
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
现在x轴在子图之间对齐,但是所有子图都是相同的大小(这不是我想要的)
此外,我希望子图在x轴上触摸如下:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = s1*s2
fig1 = plt.figure()
plt.subplots_adjust(hspace=0)
ax1 = plt.subplot(311)
ax2 = plt.subplot(312, sharex=ax1)
ax3 = plt.subplot(313, sharex=ax1)
ax1.plot(t,s1)
ax2.plot(t[:150],s2[:150])
ax3.plot(t[30:],s3[30:])
xticklabels = ax1.get_xticklabels()+ax2.get_xticklabels()
plt.setp(xticklabels, visible=False)
plt.show()
Run Code Online (Sandbox Code Playgroud)
所以重新解释我的问题:
我想用
plt.subplot2grid(..., colspan=3, rowspan=2)
plt.subplots(..., sharex=True)
plt.subplots_adjust(hspace=0)
Run Code Online (Sandbox Code Playgroud)
和
plt.tight_layout()
Run Code Online (Sandbox Code Playgroud)
在同一图中.怎么做?
Joe*_*ton 30
只需sharex=ax1在创建第二个和第三个子图时指定.
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = s1*s2
fig = plt.figure()
ax1 = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2)
ax2 = plt.subplot2grid((4,3), (2,0), colspan=3, sharex=ax1)
ax3 = plt.subplot2grid((4,3), (3,0), colspan=3, sharex=ax1)
ax1.plot(t,s1)
ax2.plot(t[:150],s2[:150])
ax3.plot(t[30:],s3[30:])
fig.subplots_adjust(hspace=0)
for ax in [ax1, ax2]:
plt.setp(ax.get_xticklabels(), visible=False)
# The y-ticks will overlap with "hspace=0", so we'll hide the bottom tick
ax.set_yticks(ax.get_yticks()[1:])
plt.show()
Run Code Online (Sandbox Code Playgroud)

如果您使用的还是什么fig.tight_layout(),你需要调用它之前 fig.subplots_adjust(hspace=0).这样做的原因是tight_layout通过自动计算参数subplots_adjust然后调用它来工作,因此如果subplots_adjust首先手动调用,则第一次调用它的任何内容都将被覆盖tight_layout.
例如
fig.tight_layout()
fig.subplots_adjust(hspace=0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13833 次 |
| 最近记录: |