gpt4 book ai didi

python - 交互式 Plotly Int slider

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:50 25 4
gpt4 key购买 nike

大家好,我对 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 的结果:

enter image description here

关于python - 交互式 Plotly Int slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50274978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com