0

In Jupyter I want to first plot via plt.scatter and then via plt.plot
but I want to show both on the same plot/figure.

I.e. I want the curve from plt.plot to appear visually on the same plot as the scatter plot.

Is that possible and how?

peter.petrov
  • 34,474
  • 11
  • 63
  • 118

1 Answers1

0

Here is a very small example:

f, ax = plt.subplots(1, 1, figsize=(5, 5))
ax.plot(x, y1)
ax.plot(x, y2)

You can replace one of the plots with a scatter plot, add others, .. In this case, ax is an axes instance however, if you specify other parameters for subplots, e.g. plt.subplots(2, 1), ax will be an iterable (numpy array) of axes instances. Thus you will need to access the ax on which you want to plot:

ax[1].plot() or if 2d ax[1, 1].plot()

Finally, the method ax.plot() takes basically the same argument than plt.plot(). However the syntax to set the title, the xlim, the ylim, the xlabel, the ylabel, is slightly different.

Example in jupyter:

enter image description here

Mathieu
  • 4,445
  • 2
  • 21
  • 43
  • The result/drawing from the 2nd plot doesn't appear visually in Jupyter. – peter.petrov Dec 22 '20 at 08:54
  • Add a plt.show()? – Mathieu Dec 22 '20 at 08:54
  • Tried it already before posting ;) No luck – peter.petrov Dec 22 '20 at 08:55
  • @peter.petrov And I believe jupyter needs a line at the top of the file in an executable cell: %matplotlib inline : c.f. https://stackoverflow.com/questions/19410042/how-to-make-ipython-notebook-matplotlib-plot-inline – Mathieu Dec 22 '20 at 08:55
  • I see the visual result but only from the 1st (scatter) plot. The second call just writes: `[]` but shows no graphical output. – peter.petrov Dec 22 '20 at 08:56
  • @peter.petrov You made me install jupyter to test it.. Works fine. – Mathieu Dec 22 '20 at 09:04
  • @peter.petrov And remove the f.show(). – Mathieu Dec 22 '20 at 09:04
  • Oh, you're doing it in a single cell, I am doing it in 2 cells (the 2 calls, I mean). – peter.petrov Dec 22 '20 at 09:07
  • if you want to update a plot with successive calls you need to tell jupyter to load an interactive backend: `%matplotlib ipympl` or `%matplotlib notebook`. If you use `%matplotlib inline`, the png image produced after the first call will not be updated automatically. – ezatterin Dec 22 '20 at 11:11
  • @peter.petrov if you are running inline then you can't run the second cell. I am inferring that you are creating the figure + axes in 1 cell, and atleast are plotting the second line in a different cell. That does not work as %matplotlib inline produces a png, although the artist is added to the axis the png is not dynamic. You can verify this by using the `%matplotlib notebook` (jupyter notbook) or `%matplotlib widget` (Jupyterlab) backends. Put the plotting in the same cell and it would work. – cvanelteren Dec 22 '20 at 12:57