matplotlib, plot through a loop resulting in connected points

Viewed 22

This is probably a question that someone has already asked, but I did not found any hint so far and it should be quite simple.

normally I plot from an array like the following:

fig = plt.figure(figsize=[5,5])
ax = fig.add_subplot(121)
ax.plot(arr[:,0], arr[:,1])

however I want to do it in a loop and get a similar result, and what I tried so far was:

fig = plt.figure(figsize=[5,5])
ax = fig.add_subplot(121)
for i in range(arr.shape[0]):
    ax.plot(arr[i,0], arr[i,1])

but it only plotted the last point.

1 Answers

The problem is that you're generating the plot using always the same axis (ax in your code). In order to print different plots as subplots, you need to use different axes. You can use matplotlib.pyplot.subplots to initialize your figure and your list of axes, then you can cycle over the axes with the for loop:

fix, axes = plt.subplots(arr.shape[0], figsize=[5,5])
for i in range(arr.shape[0]):
    ax[i].plot(arr[i,0], arr[i,1])

Does it solve your problem?

Related