Home > OS >  How would I use subplots inside a function?
How would I use subplots inside a function?

Time:08-05

I made a function to create a simple scatterplot, and when I looped through to create my graphs, the graphs came out in a straight vertical list. How would i use subplots to format the graphs to be presented in a 2x2 format rather than just a list of 4 graphs

Example

def simple_point(x,y):
    plt.plot(x,y,'ro')

coordinates =[(2,1), (2,2), (0,0), (4,4)]

for x, y in coordinates:
    simple_point(x,y)
    plt.show()

CodePudding user response:

I'd advise you to read the docs of subplots.

But as an example, something along these lines:

coordinates =[(2,1), (2,2), (0,0), (4,4)]
fig, axes = plt.subplots(nrows=2, ncols=2)

axes = axes.ravel()
for i, (x, y) in enumerate(coordinates):
    axes[i].plot(plt.plot(x, y, 'ro'))

plt.show()

CodePudding user response:

You can use subplots() function to perform the desired task. Here is the code.

import matplotlib.pyplot as plt

fig,axs = plt.subplots(2,2)
def simple_point(x,y,axs):
    graphs = [(0,0), (0,1), (1,0), (1,1)]
    for x,y in graphs:
        axs[x,y].plot(x, y, 'ro')

coordinates =[(2,1), (2,2), (0,0), (4,4)]
for x, y in coordinates:
    simple_point(x,y,axs)
    plt.show()
  • Related