简体   繁体   中英

matplotlib use single figure window for all subsequent plots

I am looking for a workflow that reuses a single window to display all plots. Subsequent plots simply overwrite the existing plot and do not block the repl. Rstudio has a single plot pane that always shows the last plot. Is a similar workflow possible from the python repl (not a notebook)?

For example, running the following code creates two windows: one for Figure1 and another Figure2. I would like the second figure to replace the existing figure and only use one window for all plotting.

import seaborn as sns
import matplotlib.pyplot as plt
data = sns.load_dataset('titanic')

sns.pairplot(data[['fare','class']])
plt.show(block=False)

sns.pairplot(data[['fare','age']])
plt.show(block=False)

After much googling and stumbling upon this excellent article I was able to find a solution to my problem. The trick is to get a reference to the figure and axis from the start to manipulate in subsequent plots.

Another key insight is to pass the axis object to the plotting methods. You can get a reference to the axis on the current figure using fig.gca() :

import matplotlib.pyplot as plt
import seaborn as sns

data = sns.load_dataset('titanic')

# create initial references
fig, ax = plt.subplots()

# pass in the current axis to the `ax` argument
sns.scatterplot(x=data['age'], y =data['age'], ax=fig.gca())
plt.draw()
plt.show(block=False)

# need to clear the figure between calls
fig.clf()
sns.scatterplot(x=data['age'], y =data['fare'], ax=fig.gca())
plt.draw()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM