1

I am trying to plot data to a figure and respective axis in matplotlib and as new work comes up, recall the figure with the additional plot on the axis:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

x=np.arange(0,20)
y=2*x

fig,ax=plt.subplots()
ax.scatter(x,x)

ax.scatter(x,y)
fig

Which works fine with matplotlib, if I however use seaborn's regplot:

fig2,ax2=plt.subplots()
sns.regplot(x,x,ax=ax2,fit_reg=False)

sns.regplot(x,y,ax=ax2,fit_reg=False)
fig2

fig2 generates the figure that I want but the regplot command generates an empty figure. Is there a way to suppress the regplot's empty output or have it display the updated ax2 without recalling fig2?

Dan Reia
  • 980
  • 9
  • 12

2 Answers2

5

It seems you are using the jupyter notebook with the inline backend. In some circumstances regplot triggers the creation of a new figure even if the artists are being added to the previous one and this messes up the output. I don't know why this happens but I found a workaround that might help you, using plt.ioff to temporarily disable automatic display of figures.

plt.ioff()
fig, ax = plt.subplots()
sns.regplot(x, x, ax=ax)
fig

sns.regplot(x, 2 * x, ax=ax)
fig

You have to call plt.ioff before creating the figure for this to work. After that you have to explicitly display the figure. Then you can call plt.ion to restore the default behaviour.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
0

regplot does not generate an empty figure. According to the documentation:

Understanding the difference between regplot() and lmplot() can be a bit tricky. In fact, they are closely related, as lmplot() uses regplot() internally and takes most of its parameters. However, regplot() is an axes-level function, so it draws directly onto an axes (either the currently active axes or the one provided by the ax parameter), while lmplot() is a figure-level function and creates its own figure, which is managed through a FacetGrid.

When I do the following:

fig2,ax2 = plt.subplots()
same_fig2 = sns.regplot(x,x,ax=ax2,fit_reg=False)

same_fig2.figure is fig2
>>> True
Ted Petrou
  • 59,042
  • 19
  • 131
  • 136
  • It could be the fact that I am running the above in a jupyter notebook, however if i run sns.regplot(x,y,ax=ax2,fit_reg=False) in a separate cell to – Dan Reia Dec 18 '16 at 10:24
  • the preceding code then an empty figure is generated. – Dan Reia Dec 18 '16 at 10:25