删除 Jupyter Notebook 中涉及交互式小部件的同一单元格中过去的 Matplotlib 图

Remove past Matplotlib plots in the same cell in Jupyter Notebook involving interactive widgets(删除 Jupyter Notebook 中涉及交互式小部件的同一单元格中过去的 Matplotlib 图)
本文介绍了删除 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.

谁能帮我解决这个问题?

Could anyone help me with this?

提前致谢.

推荐答案

您可以在函数末尾添加 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 图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)