How can I separate multiple graphs in this code?

Question:

I’m new learner of python. I am trying to split the graphs into 4 separated blocks. I know I need to use subplots but I dont know how to. Here is my code Im trying right now.

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rcParams['lines.color'] = 'k'
mpl.rcParams['axes.prop_cycle'] = mpl.cycler('color', ['k'])
x = np.linspace(-9, 9, 400)
y = np.linspace(-5, 5, 400)
x, y = np.meshgrid(x, y)

def axes():
    plt.axhline(0, alpha=.1)
    plt.axvline(0, alpha=.1)

a = 0.3
axes()
plt.contour(x, y, (y**2 - 4*a*x), [2], colors='k')
plt.show()

a1 = 2
b1= 2
axes()
plt.contour(x, y,(x**2/a1**2 + y**2/b1**2), [1], colors='k')
plt.show()

a = 4.0
b = 2.0
axes()
plt.contour(x, y,(x**2/a**2 + y**2/b**2), [1], colors='k')
plt.show()

a = 2.0
b = 1.0
axes()
plt.contour(x, y,(x**2/a**2 - y**2/b**2), [1], colors='k')
plt.show()

I’ve tried

fig, ax = plt.subplots(3, 2)

a = 0.3
axes()
ax[0].plot(x, y, (y**2 - 4*a*x), [2], colors='k')
plt.show()

and

fig, ax = plt.subplots(3, 2)

def practice():
   a = 0.3
   axes()
   ax[0].plot(x, y, (y**2 - 4*a*x), [2], colors='k')
ax[0].plot(practice)

either way dosent work

Asked By: Rozy0930

||

Answers:

plt.subplots returns a 2D array of axes.
So, you must call plot or contour on ax[i,j] i and j being integers, not on plt or ax[i].

Besides, that goes also for your axhline and axvline

Lastly, you must call plt.show() only once if you want one window to show up.

So

# Untouched code before that
def axes(ax):
    ax.axhline(0, alpha=.1)
    ax.axvline(0, alpha=.1)

fig, ax = plt.subplots(3, 2)

a = 0.3
axes(ax[0,0])
ax[0,0].contour(x, y, (y**2 - 4*a*x), [2], colors='k')

a1 = 2
b1= 2
axes(ax[0,1])
ax[0,1].contour(x, y,(x**2/a1**2 + y**2/b1**2), [1], colors='k')

a = 4.0
b = 2.0
axes(ax[1,0])
ax[1,0].contour(x, y,(x**2/a**2 + y**2/b**2), [1], colors='k')

a = 2.0
b = 1.0
axes(ax[1,1])
ax[1,1].contour(x, y,(x**2/a**2 - y**2/b**2), [1], colors='k')

plt.show()

(Note that I kept your subplots parameters, and then your 4 plots. But, of course, subplots(3,2) creates 3×2=6 subgraphs, not 4. So 2 of them remain empty after this code.

Result

Answered By: chrslg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.