Reputation: 57
I have a couple of plot scripts that using subplots
to generate figure and axis[i].grid(axis = 'y')
to show grid only for y-axis. Other works well, but I have no idea why this script doesn't show the grid line. Could someone help me?
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()
Upvotes: 2
Views: 1006
Reputation: 6922
Setting the axs[0].grid(axis = 'y')
and other axis settings outside the for loop seems to make it work, just tested it in a Jupyter notebook, e.g.:
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')
Upvotes: 2