0

I want to plot a white plot with two axes, show it to the user, then add a line to the white plot with two axes, show it to the user, then add some dot to the line, then show it to the user. How can I do this without copying the code again and again?

What I'm doing now is in the first code chunk

import math
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

fig = plt.figure(figsize=(5,5))
ax = plt.axes()

ax.set_xlabel('cat')
ax.set_ylabel('dog')

plt.title("Set of 2 animals")

plt.show()

then in the second code chunk

fig = plt.figure(figsize=(5,5))
ax = plt.axes()

x = np.linspace(0, 1.0, 1000)
ax.plot(x, 1.0-x,zorder = 0)

ax.set_xlabel('cat')
ax.set_ylabel('dog')

plt.title("Set of 2 animals")
plt.show()

then in the third code chunk

fig = plt.figure(figsize=(5,5))
ax = plt.axes()

x = np.linspace(0, 1.0, 1000)
ax.plot(x, 1.0-x,zorder = 0)

ax.set_xlabel('cat')
ax.set_ylabel('dog')

plt.title("Set of 2 animals")
p0 = 0.5
p1 = 0.5
color = "blue"
textd =0.05
ax.scatter([p0],[p1], color = color,zorder=1)
ax.text(p0+textd, p1+textd, 'tiger',color = color,zorder =2)
plt.show()

What I'm looking for is things like in the first code chunk

import math
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

fig = plt.figure(figsize=(5,5))
ax = plt.axes()

ax.set_xlabel('cat')
ax.set_ylabel('dog')

plt.title("Set of 2 animals")

plt.show()

then in the second code chunk

add line directly without duplicating the code for making axes
plt.show()

then in the third code chunk

add point directly without duplicating the code for making axes and lines
plt.show()
Jenny
  • 76
  • 8
  • I'd try not making new figures in each new code chunk. Hoewver, you will need to make sure that all the code chunks are in the same cell as in the inline backend figures are closed at the end of cell execution – Ianhi Nov 14 '20 at 04:29
  • @lanhi but I can't, I want to do a step by step demo to show how I can creat these plots – Jenny Nov 14 '20 at 18:36
  • Does this answer your question? [How to keep the current figure when using ipython notebook with %matplotlib inline?](https://stackoverflow.com/questions/31441247/how-to-keep-the-current-figure-when-using-ipython-notebook-with-matplotlib-inli) – Asmus Nov 27 '20 at 10:49

1 Answers1

0

Update: I actually figured out the answer.

def plot(step):
  fig = plt.figure(figsize=(5,5))
  ax = plt.axes()
  ax.set_xlabel('cat')
  ax.set_ylabel('dog')
  plt.title("Set of 2 animals")
  if step>=1:
    x = np.linspace(0, 1.0, 1000)
    ax.plot(x, 1.0-x,zorder = 0)
  if step>=2:
    p0 = 0.5
    p1 = 0.5
    color = "blue"
    textd =0.05
    ax.scatter([p0],[p1], color = color,zorder=1)
    ax.text(p0+textd, p1+textd, 'tiger',color = color,zorder =2)
  plot.show()

should be able to solve the problem.

Jenny
  • 76
  • 8