首页 > 解决方案 > Matplotlib,使用用户输入在循环中绘制什么

问题描述

这是我第一次在这里提出问题,所以我希望我能正确地提出任何关于清晰度的反馈。

由于我正在使用的数据结构,我被迫在我正在编写的代码中使用 matplotlib 的绘图函数。但它不适用于循环绘图。我的目标是能够修改用户确定的背景窗口,并接受或拒绝输出。但据我了解,matplotlibs 交互功能和循环的使用之间存在一些冲突。我对 python 比较陌生,所以代码可能不是最简单的,但通常我可以完成工作。然而,我对特定问题完全不知所措。我在互联网上看到过类似的问题,这些问题已通过 plt.pause('timeinterval') 解决,但在我的情况下这不是一个选项。或者至少我看不到如何使用它,因为我想等待用户输入。我也试过 plt.

我想第三种选择是从 hyperspy 使用的格式中提取数据,然后制作我自己的画布,这可以满足我的需求,但这对我来说非常繁琐,因为我缺乏经验。

有没有人有任何替代方法来制作情节,最好是使用 matplotlib,这样我就可以实现我正在尝试的东西?

顺便说一句,我也尝试过关闭交互模式,但这并没有成功。

有关规格的一些信息:这是在 windows pc 上运行,使用 jupyterlab 和 python 3.10

我希望我的困境很清楚。

def set_background(self):
    """
    This function is ment to let the user define the background of each element, and then save the background for later use
    if working with multiple images of particles with the same composition.
    This function could be expanded to have interactive features so background would be clickable.
    """
    
    
    self.Background_tree = {}
    elements_in_sample = deepcopy(self.Data.metadata.Sample['elements'])
    Xray_in_sample = self.weighted_Xray_line_list
    data_sample = deepcopy(self.Data)
    integration_window = 1.3
    for element in elements_in_sample:
        data_sample.set_elements(elements=[element])
        for xray_line in (self.Data.metadata.Sample["xray_lines"]):
            if element in xray_line:   
                data_sample.set_lines([xray_line])
                background_points = input('please input the background points seperated by a space').split(' ')
                background_window = list(map(float,background_points))
                bw = data_sample.estimate_background_windows(background_window)
                iw = data_sample.estimate_integration_windows(integration_window)
                data_sample.sum().plot(True,bakcground_windows=background_window)
                happy = input('are you happy with the result?')
                if happy == 'y':
                #self.Data.get_lines_intensity(xray_lines=[xray_line], background_windows=bw, integration_windows=iw)
                    self.Background_tree[element+"_"+xray_line] = bw  

标签: pythonmatplotlib

解决方案


import pandas as pd
import numpy as np
import ipywidgets as wg
from ipywidgets import HBox, VBox
import matplotlib.pyplot as plt
from IPython.display import display
%matplotlib widget

a = np.arange(50)
b = np.random.rand(50) + a
c = np.sin(a)
d = np.cos(b)

df = pd.DataFrame({'a': a,
                   'b': b,
                   'c': c,
                   'd': d})

userinput1 = wg.Text(value="", placeholder='Type something', description='x axis')
userinput2 = wg.Text(value="", placeholder='Type something', description='y axis')
buttonplot = wg.Button(description='Plot', disabled=False, button_style='', tooltip='Click me',icon='check')
buttonout = wg.Output()
display(HBox((userinput1, userinput2, buttonplot)))
display(buttonout)
plt.close()
fig, ax = plt.subplots()
def on_click_event(change):
    with buttonout:
        x = (userinput1.value)
        y = (userinput2.value)
        ax.plot(df[x], df[y], label=f'{y}')
        ax.legend()
buttonplot.on_click(on_click_event)

输出:

在此处输入图像描述

用户输入并单击按钮后:

在此处输入图像描述

更多用户输入:

在此处输入图像描述

它是否满足您的需求,还是我离您最初的问题越来越远?


推荐阅读