Solution: Subplots

Look into the solution of the subplots exercise.

We'll cover the following...

Solution

You can check the solution to the subplots exercise below:

Press + to interact
# import commands
import matplotlib.pyplot as plt
import numpy as np
import math
from mpl_toolkits.mplot3d import Axes3D
# create plot
gs = plt.GridSpec(3,3)
fig = plt.figure()
plt.subplots_adjust(hspace = 0.5, wspace = 0.5)
# plot 1: 3D surface plot on row # 1,2 and col # 1,2
s1 = fig.add_subplot(gs[:2,:2],projection='3d')
X = np.arange(-1,1,0.1)
Y = np.arange(-1,1,0.1)
X,Y = np.meshgrid(X,Y)
def f(x,y):
return y**2 + x**2
s1.plot_surface(X,Y,f(X,Y),cmap='viridis')
s1.view_init(elev=30,azim=210)
# plot 2: Polar plot on row # 1 and col # 3
s2 = fig.add_subplot(gs[0,2],polar=True)
t = np.arange(0, 360, 0.02)
r = 0.5*t/60
plt.polar(np.radians(t), r)
# plot 3: horizontal bar plot on row # 2 and col # 3
s3 = fig.add_subplot(gs[1,2])
index = np.arange(1,6)
values = np.array([6,2,7,3,8])
plt.barh(index,values,color = (.42, .37, .73))
plt.yticks(index,['A','B','C','D','E'])
plt.xlim(0,10)
# plot 4: 2D Scatter plot on row # 3 and col # 1,2,3
s4 = fig.add_subplot(gs[2,:3])
t = np.arange(0,2.6,0.1)
y1 = list(map(math.sin,math.pi*t))
y2 = list(map(math.sin,math.pi*t+math.pi/2))
y3 = list(map(math.sin,math.pi*t-math.pi/2))
plt.plot(t,y1,'b*',t,y2,'g^',t,y3,'rs')
plt.savefig('output/subplot.png')

Explanation

In the code above:

  • Lines 2–5: We import the necessary ...