在Jupyter Notebook的同一单元中删除涉及交互式小部件的过去Matplotlib图 [英] Remove past Matplotlib plots in the same cell in Jupyter Notebook involving interactive widgets

查看:116
本文介绍了在Jupyter Notebook的同一单元中删除涉及交互式小部件的过去Matplotlib图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是一个小问题,困扰了我一段时间.

this is just a small problem that has been bugging me for a while.

我有一个由所有连续变量组成的熊猫数据框.我想为任意选择的变量对绘制散点图(使用matplotlib),同时还要利用Jupyter中的交互式小部件.

I have a pandas dataframe consisting of all continuous variables. I want to draw a scatter plot (using matplotlib) for any chosen pair of variables, making use of the interactive widgets in Jupyter as well.

假设数据具有3个数字列:"a","b"和"c".

Let's say the data has 3 numeric columns: 'a','b', and 'c'.

到目前为止,我有以下几行代码:

So far I have these lines of codes:

def g(x,y):
    plt.scatter(x, y)
interactive_plot = interactive(g, x=['a','b','c'], y=['a','b','c'])
interactive_plot

它们运行良好,因为每当我使用x和y的下拉框进行切换并从3个可用变量中选择一对变量时,它们便会绘制散点图.但是,这里的问题在于,在显示新图之前,不会擦除之前搅动过的图.换句话说,matplotlib不会更新现有图中的绘图,而只是将绘图/图形彼此叠加.因此,如果我将变量对的选择更改10次,我会得到10个散点图,这不是我想要的.

And they work fine, as in they do churn out a scatter plot whenever I toggle with the drop-down boxes for x and y and select a pair of variables from the 3 variables available. However, the problem here is that previous plots churned out are not erased before a new plot is shown. In other words, matplotlib doesn't update the plot in the existing figure, but simply stack plots/figures on top of each other. So if I change the choice of variable pairs 10 times, I'll get 10 scatter plots, which isn't what I want.

有人可以帮我吗?

谢谢.

推荐答案

您可以在函数末尾添加plt.show().这会将图重新绘制在同一单元格中,而不是添加一个新的图元.

You may add plt.show() at the end of your function. This replots the graph in the same cell instead of adding a new one.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from ipywidgets import interactive
%matplotlib inline

columns=['a','b','c']
data = np.cumsum(np.random.rand(10,3),axis=1)
df = pd.DataFrame(data,columns=columns)

def g(x,y):
    plt.scatter(df[x], df[y])
    plt.show()

interactive_plot = interactive(g, x=columns, y=columns)
interactive_plot

这篇关于在Jupyter Notebook的同一单元中删除涉及交互式小部件的过去Matplotlib图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆