I want to make common settings such as grids and labels for all axes drawn with matplotlib subplot.
# 1.Get a list of axes
axs = plt.gcf().get_axes()
# 2.Loop for each axis
for ax in axs:
# 3.Change current axis
plt.axes(ax)
import matplotlib.pyplot as plt
import numpy as np
#data
x = np.linspace(-np.pi, np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# figure
plt.figure(figsize=(8,4))
#Plot 1
plt.subplot(1,2,1)
plt.plot(x,y1,label='sin')
#Plot 2
plt.subplot(1,2,2)
plt.plot(x,y2,label='cos')
#Get a list of axes
axs = plt.gcf().get_axes()
#Loop for each axis
for ax in axs:
#Change current axis
plt.axes(ax)
#Show legend
plt.legend(loc=2)
#grid
plt.grid(linestyle='--')
#Axis label
plt.xlabel('x')
plt.ylabel('y')
#Axis range
plt.xlim([-np.pi, np.pi])
plt.ylim([ -1.2, 1.2])
#Adjustment of figure
plt.tight_layout()
# 1.List data and labels.
Y = [y1, y2]
lbls = ['sin', 'cos']
# 2.Loop with enumerate
for i, y in enumerate(Y):
# 3. plt.subplot is+Don't forget to
plt.subplot(1,2,i+1)
# figure
plt.figure(figsize=(8,4))
# list
Y = [y1, y2]
lbls = ['sin', 'cos']
for i, y in enumerate(Y):
#Subplot
plt.subplot(1,2,i+1)
#plot
plt.plot(x,y,label=lbls[i])
#Show legend
plt.legend(loc=2)
#grid
plt.grid(linestyle='--')
#Axis label
plt.xlabel('x')
plt.ylabel('y')
#Axis range
plt.xlim([-np.pi, np.pi])
plt.ylim([ -1.2, 1.2])
#Adjustment of figure
plt.tight_layout()
gca, gcf You can get the current figure with plt.gcf () and the current axes with plt.gca (). You can also specify the current axis with plt.axes ().
Like MATLAB, matplotlib's figure has a hierarchical structure as shown in the figure below.
There are axes in the figure and lines in the axes. You can get a list of all the axes in the current figure with plt.gcf (). get_axes (). Besides, plt.gca (). get_lines () can get all the lines in the current axes.
Recommended Posts