110

I want to plot multiple data sets on the same scatter plot:

cases = scatter(x[:4], y[:4], s=10, c='b', marker="s")
controls = scatter(x[4:], y[4:], s=10, c='r', marker="o")

show()

The above only shows the most recent scatter()

I've also tried:

plt = subplot(111)
plt.scatter(x[:4], y[:4], s=10, c='b', marker="s")
plt.scatter(x[4:], y[4:], s=10, c='r', marker="o")
show()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Austin Richardson
  • 8,078
  • 13
  • 43
  • 49

4 Answers4

171

You need a reference to an Axes object to keep drawing on the same subplot.

import matplotlib.pyplot as plt

x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')
plt.legend(loc='upper left')
plt.show()

enter image description here

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
nate c
  • 8,802
  • 2
  • 27
  • 28
  • 23
    What does `111` in `fig.add_subplot(111)` mean ? – Temak Nov 18 '15 at 18:49
  • 9
    It's the arrangement of subgraphs within this graph. The first number is how many rows of subplots; the second number is how many columns of subplots; the third number is the subgraph you're talking about now. In this case, there's one row and one column of subgraphs (i.e. one subgraph) and the axes are talking about the first of them. Something like fig.add_subplot(3,2,5) would be the lower-left subplot in a grid of three rows and two columns. – Neil Smith Nov 27 '15 at 16:10
  • 2
    What if I need to plot three scatter plots instead of two shown here? – NixMan Feb 10 '21 at 10:38
  • @NixMan nothing changes, it works with the same setting – MJimitater Jun 08 '21 at 08:48
40

I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
Sohaib Farooqi
  • 5,457
  • 4
  • 31
  • 43
  • Can I use the same approach for a third scatter plot? Like, plt.scatter(x, y, c='g', marker='o', label='-2') – NixMan Feb 10 '21 at 11:06
9

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()
Steve Tjoa
  • 59,122
  • 18
  • 90
  • 101
3

You can also do this easily in Pandas, if your data is represented in a Dataframe, as described here:

http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#scatter-plot

MaVe
  • 1,715
  • 5
  • 21
  • 29