0

I'm trying to add a point to a scatterplot that I've already displayed. For simplicity, I'd rather not recreate the plot shown previously, but rather display a previous plot and not have it cleared.

For example: Here is my first plot...

fig, ax = plt.subplots(1,1) 

ax.scatter(owners.Income, owners.Lot_Size, marker='o', label='Owner', color='C1')
ax.scatter(nonowners.Income, nonowners.Lot_Size, marker='D', label='Nonowner', color='C0')

plt.xlabel('Income')  # set x-axis label
plt.ylabel('Lot_Size')  # set y-axis label

# iterate through each row and add the number of each observation to the scatter plot
for index, row in train_data.iterrows(): # look through each row of our data
    ax.annotate(index, (row.Income + 1, row.Lot_Size)) # add the number of the observation next to point


handles, labels = ax.get_legend_handles_labels() # add a legend
ax.legend(handles, labels, loc=4)

ax.set_xlim(40, 115) # set the x range

plt.show() 

Then, what I'd like to do in the next code cell is to display a new point on this existing figure/ax....

new_household = pd.DataFrame([{'Income': 60, 'Lot_Size': 20}])
new_household

ax.scatter(new_household.Income, new_household.Lot_Size, marker='*', label='New household', color='black', s=150)

plt.show() # nothing displays, since the previous figure is now cleared

The second plot doesn't display because the previous figure has been cleared by the plt.show function.

How can I show the first scatterplot, but keep the figure and ax's so that I can continue add to the plot in later cells (without having to recreate the complete plot each time)?

tcs
  • 353
  • 1
  • 3
  • 11
  • Does this answer your question? [python matplotlib update scatter plot from a function](https://stackoverflow.com/questions/42722691/python-matplotlib-update-scatter-plot-from-a-function) – gboffi Sep 10 '22 at 16:08
  • @gboffi no, this doesn't fit (or work) for what I'm trying to do (but thank you for the link, and response). Basically, in a Jupyter notebook, I need to create and display a plot in one code cell, THEN in a separate code cell (immediately after) add to the previously displayed plot but as a new second plot (right now, the only way seems to be to repeat all the code for the initial plot, and then add what I need). The issue is that once plot is called and I exit the cell, all fig/ax data is cleared. – tcs Sep 10 '22 at 17:39

0 Answers0