我正在使用一个 csv 文件,其中包含一家精酿啤酒厂的啤酒销售情况。这些物品按“次要”和“主要”类型分类,因为有一些非酒精产品出售。但我不确定如何让条形图仅使用主要类别类型进行更新...
理想情况下,我尝试按次要类别显示每个选定主要类别的销售数据。代码在这里提供:
# Import required libraries
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
import plotly.express as px
import plotly.graph_objects as go
file_loc = "https://raw.githubusercontent.com/Barbj379/Two_Ton/main/Item%20Sales%20Report.csv"
df = pd.read_csv(file_loc)
# Create a dash application
app = JupyterDash(__name__)
app.layout= html.Div(children=[
# New Div for all elements in the new 'row' of the page
html.Div([
html.H1(children='Two Ton Dash'),
html.Div(children='''
Sales report of last fiscal quarter.
'''),
html.Div([dcc.Graph(id='graph0'),
html.Label(["Category",
dcc.Dropdown(
id='category-dropdown', clearable=False,
value='ALCOHOL', options=[
{'label': c, 'value': c}
for c in df['Major Category'].unique()])
]),
]),
])
])
# Callback function that automatically updates the tip-graph based on chosen colorscale
@app.callback(
Output('graph0', 'figure'),
[Input("category-dropdown", "value")]
)
def update_figure(Category):
new_df = df.groupby(['Minor Category', 'Item Name'])['Net Sales'].sum().reset_index()
new_df.reset_index()
fig=px.bar(
new_df, x="Minor Category", y="Net Sales", color="Item Name",
color_continuous_scale=Category,
title="Items")
return fig
if __name__ == '__main__':
app.run_server(debug=True)
# Create an app layout
当我运行提供的代码时,会出现一个条形图,显示商品名称销售额的总和,按次要类别类型分组;但下拉菜单不会过滤掉任何内容。为这样的菜鸟道歉!
You should filter your data with
Category
value before groupby it.您可以按以下方式更新您的回调:
@app.callback(
Output('graph0', 'figure'),
[Input("category-dropdown", "value")]
)
def update_figure(Category):
new_df = df[df['Major Category']==Category]
new_df = new_df.groupby(['Minor Category', 'Item Name'])['Net Sales'].sum().reset_index()
new_df.reset_index()
fig=px.bar(
new_df, x="Minor Category", y="Net Sales", color="Item Name",
color_continuous_scale=Category,
title="Items")
return fig