BenH
BenH

Reputation: 2120

How do I display multiple matplotlib.pyplot plots in the same figure?

I'm making three scatter plots, and I'd like them to all show up in the same window (but not in the same plot). Right now, three separate windows pop up, one for each plot. If I move matplotlib.pyplot.show() outside the loop, then they are all plotted on the same set of axes.

import matplotlib.pyplot

time = [1,2,3]
value = {}
value['x'] = [1,2,3]
value['y'] = [1,4,9]
value['z'] = [1,8,27]
for dimension in ['x', 'y', 'z']:
    matplotlib.pyplot.scatter(time, value[dimension])
    matplotlib.pyplot.show()

Upvotes: 1

Views: 6222

Answers (2)

Salt_from_the_Sea
Salt_from_the_Sea

Reputation: 41

I think there has been a python version change that breaks the above code, it did not run for me because enumerate now starts at 0, for example enumerate(iterable, start=0) is the base case, so I made the following modification and it ran:

import matplotlib.pyplot as plt

time = [1,2,3]
value = {}
value['x'] = [1,2,3]
value['y'] = [1,4,9]
value['z'] = [1,8,27]
for k, dimension in enumerate(['x', 'y', 'z'], 1):
#     print(k, dimension)
    plt.subplot(3, 1, k)
    plt.scatter(time, value[dimension])

plt.show()

Upvotes: 1

David Zwicker
David Zwicker

Reputation: 24268

use subplot to create subplots:

import matplotlib.pyplot as plt

time = [1,2,3]
value = {}
value['x'] = [1,2,3]
value['y'] = [1,4,9]
value['z'] = [1,8,27]
for k, dimension in enumerate(['x', 'y', 'z']):
    plt.subplot(3, 1, k)
    plt.scatter(time, value[dimension])

plt.show()

Upvotes: 4

Related Questions