gpt4 book ai didi

python - Plotly 图表的下拉菜单

转载 作者:行者123 更新时间:2023-12-04 14:09:21 24 4
gpt4 key购买 nike

这是我的数据框:

df = pd.DataFrame({"Date":["2020-01-27","2020-02-27","2020-03-27","2020-04-27", "2020-05-27", "2020-06-27", "2020-07-27",
"2020-01-27","2020-02-27","2020-03-27","2020-04-27", "2020-05-27", "2020-06-27", "2020-07-27"],
"A_item":[2, 8, 0, 1, 8, 10, 4, 7, 2, 15, 5, 12, 10, 7],
"B_item":[1, 7, 10, 6, 5, 9, 2, 5, 6, 1, 2, 6, 15, 8],
"C_item":[9, 2, 9, 3, 9, 18, 7, 2, 8, 1, 2, 8, 1, 3],
"Channel_type":["Chanel_1", "Chanel_1", "Chanel_1", "Chanel_1", "Chanel_1", "Chanel_1", "Chanel_1",
"Chanel_2", "Chanel_2", "Chanel_2", "Chanel_2", "Chanel_2", "Chanel_2", "Chanel_2"]
})

我想在 Channel_type 列上绘制一个带有下拉过滤器的组条形图。这就是我正在尝试的:

trace2 = go.Bar(x=df["Date"], y=df[["B_item"]])
trace3 = go.Bar(x=df["Date"], y=df[["C_item"]])

list_updatemenus = [{'label': 'All',
'method': 'update',
'args': [{'visible': [True, True]}, {'title': 'All'}]},
{'label': 'Chanel_1',
'method': 'update',
'args': [{'visible': [True, False]}, {'title': 'Chanel_1'}]},
{'label': 'Chanel_2',
'method': 'update',
'args': [{'visible': [False, True]}, {'title': 'Chanel_2'}]}]


data = [trace1,trace2,trace3]

layout=go.Layout(title='Distribution of Sales by Region',updatemenus=list([dict(buttons= list_updatemenus)]),width=1000,height=800,barmode='group')


fig = go.Figure(data,layout)

fig.show()

并没有得到想要的输出:Plot 1

因为它按 "A_item""B_item""C_item" 过滤图表,而我想按提到的 Channel_type 列。

所以理想的结果应该是下图,但是下拉菜单会根据 Channel_type 更改图表:

Plot 2

我能够在 Jupyter notebook 中使用 Ipywidgets 解决问题,但它并不真正适合我的特定任务。这是代码:

from plotly import graph_objs as go
import ipywidgets as w
from IPython.display import display

x = 'Date'
y1 = 'A_item'
y2 = 'B_item'
y3 = 'C_item'

trace1 = {
'x': df[x],
'y': df[y1],
'type': 'bar',
'name':'A_item'
}

trace2={
'x': df[x],
'y': df[y2],
'type': 'bar',
'name':'B_item'
}

trace3 = {
'x': df[x],
'y': df[y3],
'type': 'bar',
'name':'C_item',

}

data = [trace1, trace2, trace3]

# Create layout for the plot
layout=dict(
title='Channels',
width=1200, height=700, title_x=0.5,
paper_bgcolor='#fff',
plot_bgcolor="#fff",
xaxis=dict(
title='Date',
type='date',
tickformat='%Y-%m-%d',
gridcolor='rgb(255,255,255)',
zeroline= False,
),
yaxis=dict(
title='My Y-axis',
zeroline= False
)
)

fig = go.FigureWidget(data=data, layout=layout)

def update_fig(change):
aux_df = df[df.Channel_type.isin(change['new'])]
with fig.batch_update():
for trace, column in zip(fig.data, [y1, y2, y3]):
trace.x = aux_df[x]
trace.y = aux_df[column]

drop = w.Dropdown(options=[
('All', ['Chanel_1', 'Chanel_2']),
('Chanel_1', ['Chanel_1']),
('Chanel_2', ['Chanel_2']),
])
drop.observe(update_fig, names='value')



display(w.VBox([drop, fig]))

这是输出:

Output

问题是我无法将 VBox 包装到 HTML 文件中并保存下拉菜单。此外,它不适用于 Python shell,因为它适用于 Jupyter notebook,我需要分享它。

因此,理想的结果是只将最后一个图形包裹在 Plotly fig 中,而没有 ipywidgets。

非常感谢任何帮助!

谢谢!

最佳答案

要注意的最重要的一点是,对于 go.Bar,如果您在 x 参数中有 n 个日期,并且您传递了一个维度 (m, n) 到 go.Bary 参数的二维数组,Plotly 理解创建一个分组条形图,每个日期 n 都有 m 条。

对于您的 DataFrame,df[df['Channel_type'] == "Channel_1"][items].T.values 之类的东西将根据需要 reshape 它。所以我们可以将它应用到我们传递给我们制作的按钮的 argsy 字段。

感谢@veSTLand 对按钮进行调整以使其成为下拉菜单的代码部分。

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({"Date":["2020-01-27","2020-02-27","2020-03-27","2020-04-27", "2020-05-27", "2020-06-27", "2020-07-27",
"2020-01-27","2020-02-27","2020-03-27","2020-04-27", "2020-05-27", "2020-06-27", "2020-07-27"],
"A_item":[2, 8, 0, 1, 8, 10, 4, 7, 2, 15, 5, 12, 10, 7],
"B_item":[1, 7, 10, 6, 5, 9, 2, 5, 6, 1, 2, 6, 15, 8],
"C_item":[9, 2, 9, 3, 9, 18, 7, 2, 8, 1, 2, 8, 1, 3],
"Channel_type":["Channel_1", "Channel_1", "Channel_1", "Channel_1", "Channel_1", "Channel_1", "Channel_1",
"Channel_2", "Channel_2", "Channel_2", "Channel_2", "Channel_2", "Channel_2", "Channel_2"]
})

fig = go.Figure()

colors = ['#636efa','#ef553b','#00cc96']
items = ["A_item","B_item","C_item"]
for item, color in zip(items, colors):
fig.add_trace(go.Bar(
x=df["Date"], y=df[item], marker_color=color
))

# one button for each df column
# slice the DataFrame and apply transpose to reshape it correctly
updatemenu= []
buttons=[]
for channel in df['Channel_type'].unique():
buttons.append(dict(method='update',
label=channel,
args=[{
'y': df[df['Channel_type'] == channel][items].T.values
}])
)

## add a button for both channels
buttons.append(dict(
method='update',
label='Both Channels',
args=[{
'y': df[items].T.values
}])
)

# some adjustments to the updatemenu
# from code by vestland
updatemenu=[]
your_menu=dict()
updatemenu.append(your_menu)
updatemenu[0]['buttons']=buttons
updatemenu[0]['direction']='down'
updatemenu[0]['showactive']=True

fig.update_layout(updatemenus=updatemenu)

fig.show()

enter image description here

关于python - Plotly 图表的下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65670966/

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