Matplotlib: Adding a point to an existing scatterplot that has already been displayed (without needing to recreate)

Viewed 16

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)?

0 Answers
Related