Skip to main content
 首页 » 编程设计

python之交互式 Plotly Int slider

2024年12月31日14zhwl

大家好,我对 Python、Plotly 和 Jupyter Notebook 还很陌生。我想使用 slider 选择天数作为查询中的范围,从中创建图表。我唯一的问题是我希望图形在与 slider 交互时自动更新,而不必重新运行查询和图形创建。我的代码如下:

slider = widgets.IntSlider() 
display(slider) 
sliderVal = slider.value 
 
df = pd.read_sql(f""" 
SELECT CASE WHEN SiteID LIKE 3 THEN 'BLAH'  
        WHEN SiteID LIKE 4 THEN 'BLAHBLAH'  
        END AS Website,  
        COUNT(1) AS Count 
FROM            viewName 
WHERE        (TimeStamp > DATEADD(DAY, -{sliderVal}, GETDATE())) 
GROUP BY SiteId 
ORDER BY Count DESC 
           """, conn) 
 
data = [go.Bar(x=df.Website, y=df.Count)] 
layout = go.Layout( 
    xaxis=dict( 
        title='Website'), 
    yaxis=dict( 
        title='Exception count'), 
    title=f'Number of exceptions per user in the last {sliderVal} days') 
chart = go.Figure(data=data, layout=layout, ) 
py.iplot(chart, filename='WebExceptions') 

提前致谢!

请您参考如下方法:

如果您不想重新运行查询,那么您的数据框 df 必须包含您希望 intslider 小部件采用的所有值的结果,然后链接到小部件的函数将只需过滤数据并使用新的过滤数据重新绘制图形。

这是一个带有一些虚拟数据的例子:

import ipywidgets as widgets 
import plotly.offline as py 
import plotly.graph_objs as go 
import pandas as pd 
py.init_notebook_mode(connected = True) 
 
# Dummy data, to be replaced with your query result for the range of sliderVal 
df = pd.DataFrame({'Days': [1] * 3 + [2] * 4 + [3] * 5, 
                  'Website': [1,2,3, 4,5,6,7, 8,9,10,11,12], 
                  'Count': [10,5,30, 15,20,25,12, 18,17,30,23,27]}) 
 
def update_plot(sliderVal): 
    filtered_df = df.query('Days== ' + str(sliderVal)) 
    data = [go.Bar(x = filtered_df.Website, 
                   y = filtered_df.Count)] 
    layout = go.Layout( 
        xaxis = dict(title = 'Website'), 
        yaxis = dict(title = 'Exception count'), 
        title = f'Number of exceptions per user in the last {sliderVal} days') 
    chart = go.Figure(data = data, layout = layout, ) 
    py.iplot(chart, filename = 'WebExceptions') 
 
# links an IntSlider taking values between 1 and 3 to the update_plot function 
widgets.interact(update_plot, sliderVal = (1, 3)) 

这是 sliderVal = 2 的结果: