gpt4 book ai didi

python - 使用 gridspec 添加数字

转载 作者:行者123 更新时间:2023-12-01 03:08:02 25 4
gpt4 key购买 nike

我正在尝试创建一个类似于以下内容的情节 this question .

为什么我只得到两个面板,即只有 gs2:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def main():
fig = plt.figure()
gs1 = gridspec.GridSpec(1,4)
gs2 = gridspec.GridSpec(2,4)

for n in range(4):
ax00 = plt.subplot(gs1[0,n])
ax10 = plt.subplot(gs2[0,n])
ax11 = plt.subplot(gs2[1,n])

ax00.plot([0,0],[0,1*n],color='r')
ax10.plot([0,1],[0,2*n],color='b')
ax11.plot([0,1],[0,3*n],color='g')
plt.show()

main()

这给了我这个:

enter image description here

最后我想要一个像这样的数字:

enter image description here

我使用问题末尾的代码获得的。不过,我希望具有 gs2.update(hspace=0) 给出的绘图的可移动性(这就是我尝试使用 gridspec 的原因)。 IE。我想删除最后一行和第二行之间的空格。

def whatIwant():
f, axarr = plt.subplots(3,4)

for i in range(4):
axarr[0][i].plot([0,0],[0,1*i],color='r')
axarr[1][i].plot([0,1],[0,2*i],color='b') #remove the space between those and be able to move the plots where I want
axarr[2][i].plot([0,1],[0,3*i],color='g')
plt.show()

最佳答案

这确实是其中一种情况,使用 GridSpecFromSubplotSpec 是有意义的。也就是说,您将创建一个包含 1 列和 2 行(以及 1 比 2 的高度比)的总体 GridSpec。在第一行中,您将放置一个 GridSpecFromSubplotSpec ,其中包含一行 4 列。在第二行中,您将放置一个 2 行 4 列的行,另外指定 hspace=0.0 ,以便底部的两行之间没有任何间距。

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec


fig = plt.figure()

gs = gridspec.GridSpec(2, 1, height_ratios=[1,2])
gs0 = gridspec.GridSpecFromSubplotSpec(1, 4, subplot_spec=gs[0], wspace=0.4)
gs1 = gridspec.GridSpecFromSubplotSpec(2, 4, subplot_spec=gs[1], hspace=0.0, wspace=0.4)

for n in range(4):
ax00 = plt.subplot(gs0[0,n])
ax10 = plt.subplot(gs1[0,n])
ax11 = plt.subplot(gs1[1,n], sharex=ax10)
plt.setp(ax10.get_xticklabels(), visible=False)
ax00.plot([0,0],[0,1*n],color='r')
ax10.plot([0,1],[0,2*n],color='b')
ax11.plot([0,1],[0,3*n],color='g')
plt.show()

enter image description here

与链接问题的答案中的解决方案相比,此解决方案的优点是您不会重叠 GridSpec,因此不需要考虑它们如何相互关联。

<小时/>如果您仍然对问题中的代码不起作用的原因感兴趣:
您需要使用两个不同的 GridSpec,每个 GridSpec 都有总行数(在本例中为 3);但随后仅填充第一个 GridSpec 的第一行和第二个 GridSpec 的后两行:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def main():
fig = plt.figure()
gs1 = gridspec.GridSpec(3,4)
gs2 = gridspec.GridSpec(3,4, hspace=0.0)

for n in range(4):
ax00 = plt.subplot(gs1[0,n])
ax10 = plt.subplot(gs2[1,n])
ax11 = plt.subplot(gs2[2,n])

ax00.plot([0,0],[0,1*n],color='r')
ax10.plot([0,1],[0,2*n],color='b')
ax11.plot([0,1],[0,3*n],color='g')
plt.show()

main()

关于python - 使用 gridspec 添加数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43147850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com