You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PyQt5嵌入Seaborn折线图动态更新时遇警告及切换X轴变量崩溃问题求助

PyQt5嵌入Seaborn折线图动态更新时遇警告及切换X轴变量崩溃问题求助

我正在开发一个可以快速可视化CSV数据、还能轻松导出标准样式用于后续处理的PyQt5应用。我选了Seaborn来做绘图工具,因为它和DataFrame的适配性很棒,画出来的图也美观。目前散点图功能完全正常,但在实现折线图的时候碰到了两个棘手的问题:

  1. 每次更新折线图都会弹出一个FutureWarning
  2. 切换X轴变量的时候,程序大概率会直接崩溃

我已经做过的尝试:

  • 写了过滤非数值数据的函数,但没起作用,现在传入绘图的DataFrame里只包含float类型的数据
  • 处理了y变量为空的边界情况(当没选y变量时,把x变量作为y变量来避免崩溃)
  • 把DataFrame转成了长格式(melt)来适配Seaborn的绘图逻辑

出现的警告信息

FutureWarning: use_inf_as_na option is deprecated and will be removed in a future version.
Convert inf values to NaN before operating instead.
with pd.option_context('mode.use_inf_as_na', True):

核心绘图代码

def update(self):
    self.ax.clear()

    #If no y_variables are selected, use x_variable as the y_variable -> otherwise will crash
    if not self.plot_variables["y_variables"]:
        y_variables = [self.plot_variables["x_variable"]]
    else:
        y_variables = self.plot_variables["y_variables"]
    
    #Melting dataframe for easy plotting with seaborn
    long_data = self.dataframe.melt(
        id_vars=[self.plot_variables["x_variable"]],
        value_vars=y_variables, 
        var_name='y_variable',
        value_name='value'
    )
        
    sns.lineplot(
        data=long_data,
        x=self.plot_variables["x_variable"],
        y='value',
        hue='y_variable',
        ax=self.ax
    )
    
    #Update labels and title if available
    if self.plot_variables["x_label"]:
        self.ax.set_xlabel(self.plot_variables["x_label"])
    if self.plot_variables["y_label"]:
        self.ax.set_ylabel(self.plot_variables["y_label"])
    if self.plot_variables["title"]:
        self.ax.set_title(self.plot_variables["title"])
    
    #Add the legend
    self.ax.legend()
    
    #Redraw the canvas
    self.fig.canvas.draw_idle()

补充说明:

  • self.plot_variables里存的是用户选择的参数:x轴变量、y轴变量列表、x/y标签、标题等
  • 散点图用同样的DataFrame处理逻辑完全没问题,所以我怀疑是不是Seaborn lineplot的用法哪里出错了?有没有同学碰到过类似的问题,或者能帮我排查下问题出在哪?

备注:内容来源于stack exchange,提问作者Mats Baten

火山引擎 最新活动