gpt4 book ai didi

Python 子图无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:45 24 4
gpt4 key购买 nike

我试图在一个图中的三个子图中绘制三个不同的图表。我还希望第一个图形的宽度是其他两个图形的两倍。因此我使用了

gs = gridspec.GridSpec(2, 2, width_ratios=[2,1], height_ratios=[1,1])

但是输出将所有数字绘制在 ax3 上。

enter image description here

这里给出了我的代码

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

gs = gridspec.GridSpec(2, 2, width_ratios=[2,1], height_ratios=[1,1])
ax1=plt.subplot(gs[:,:-1])
ax2=plt.subplot(gs[:-1,-1])
ax3=plt.subplot(gs[-1,-1])


# ax 1
X=np.linspace(0,10,100)
Y=np.sin(X)
ax1 = plt.gca()
ax1.scatter(X, Y)
ax1.axis("tight")
ax1.set_title('ax1')
ax1.set_xlim([0,10])
ax1.set_ylim([-1,1])
plt.xticks([])
plt.yticks([])


# ax 2
ax2 = plt.gca()
vel=np.random.rand(1000)
n, bins, patches = plt.hist(vel, 10, normed=True, histtype='stepfilled', facecolor='green', alpha=1.0)
ax2.set_title('Velocity Distribution')
ax2.axis("tight")
plt.xticks([0,0.05,0.10])
plt.yticks([0,10,20])


# ax 3
Z=np.exp(X)
ax3.plot(X,Z,'red',lw=5)

plt.show()

有人可以告诉我如何纠正这个问题吗?预先感谢您。

最佳答案

修复了几行。请与您的代码进行比较。

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


gs = gridspec.GridSpec(2, 2, width_ratios=[2,1], height_ratios=[1,1])
ax1=plt.subplot(gs[:,:-1])
ax2=plt.subplot(gs[:-1,-1])
ax3=plt.subplot(gs[-1,-1])


# ax 1
X=np.linspace(0,10,100)
Y=np.sin(X)
#ax1 = plt.gca()
ax1.scatter(X, Y)
ax1.axis("tight")
ax1.set_title('ax1')
ax1.set_xlim([0,10])
ax1.set_ylim([-1,1])
# You can use ax1.set_xticks() and ax1.set_xticklabels() instead.
ax1.set_xticks([])
ax1.set_yticks([])
#plt.xticks([])
#plt.yticks([])


# ax 2
#ax2 = plt.gca()
vel=np.random.rand(1000)
n, bins, patches = ax2.hist(vel, 10, normed=True, histtype='stepfilled', facecolor='green', alpha=1.0)
ax2.set_title('Velocity Distribution')
ax2.axis("tight")
# You can use ax2.set_xticks() and ax2.set_xticklabels() instead.
ax2.set_xticks([0,0.5,1])
ax2.set_yticks([0,1,2])
#plt.xticks([0,0.05,0.10])
#plt.yticks([0,10,20])


# ax 3
Z=np.exp(X)
ax3.plot(X, Z,'red', lw=5)
# You can use ax3.set_xticks() and ax3.set_xticklabels() instead.
ax3.set_xticks([0, 5, 10])
ax3.set_yticks([0, 10000, 20000])
ax3.set_yticklabels(['0', '10K', '20K'])

plt.show()

enter image description here

关于Python 子图无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37071112/

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