gpt4 book ai didi

python - 如何在matplotlib中显示Y轴的网格线

转载 作者:行者123 更新时间:2023-12-04 09:00:26 25 4
gpt4 key购买 nike

我有几个情节脚本使用 subplots生成图形和 axis[i].grid(axis = 'y')仅显示 y 轴的网格。其他工作正常,但我不知道为什么这个脚本不显示网格线。有人可以帮助我吗?

import matplotlib.pyplot as plt
import numpy as np
nel = 8
npts = 10
h = 1./nel

x = np.zeros((npts+1, nel))
x_c = np.zeros(nel)
for i in range(0, nel):
x[:,i] = np.linspace(i*h, (i+1)*h, npts+1)
x_c[i] = (i+0.5) * h

print(x)
print(x_c)
# 3rd order DGD basis
fig, axs = plt.subplots(2, 1, sharex = True, figsize = (6,10), facecolor = 'w')
plt.tight_layout()
fig.subplots_adjust(hspace = 0)

y = np.zeros((npts+1, nel)) # for 0th element
y[:,0] = (x[:,0] - x_c[1]) * (x[:,0] - x_c[2]) * (x[:,0] - x_c[3])/(-6*h**3)
y[:,1] = (x[:,1] - x_c[1]) * (x[:,1] - x_c[2]) * (x[:,1] - x_c[3])/(-6*h**3)
for j in range(0,nel):
axs[0].plot(x[:,j], y[:,j], 'r-', linewidth=2)
axs[0].set_xticks(np.arange(0, 1.01, h))
axs[0].set_yticks(np.arange(0, 1.2, 1.0))
axs[0].set_ylim(-0.5, 1.5)
axs[0].grid(axis = 'y')

y = np.zeros((npts+1, nel)) # for 1st element
y[:,0] = (x[:,0] - x_c[0]) * (x[:,0] - x_c[2]) * (x[:,0] - x_c[3])/(2*h**3)
y[:,1] = (x[:,1] - x_c[0]) * (x[:,1] - x_c[2]) * (x[:,1] - x_c[3])/(2*h**3)
y[:,2] = (x[:,2] - x_c[2]) * (x[:,2] - x_c[3]) * (x[:,2] - x_c[4])/(-6*h**3)
for j in range(0,nel):
axs[1].plot(x[:,j], y[:,j],'r-', linewidth=2)
axs[1].set_xticks(np.arange(0, 1.01, h))
axs[1].set_yticks(np.arange(0, 1.2, 1.0))
axs[1].set_ylim(-0.5, 1.5)
axs[1].grid(axis = 'y')

plt.show()

最佳答案

设置 axs[0].grid(axis = 'y') for 循环之外的其他轴设置似乎使它工作,只是在 Jupyter 笔记本中对其进行了测试,例如:

for j in range(0,nel):
axs[0].plot(x[:,j], y[:,j], 'r-', linewidth=2)
axs[0].set_xticks(np.arange(0, 1.01, h))

axs[0].set_yticks(np.arange(0, 1.2, 1.0))
axs[0].set_ylim(-0.5, 1.5)
axs[0].grid(axis = 'y')

关于python - 如何在matplotlib中显示Y轴的网格线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63588175/

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