尝试从df获取一个值,用作指示器轴中轴范围的值

2024-06-02 05:36:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试制作一款绘图绘本的Dash应用程序,它将调出我们客户的当前小时数和历史小时数,当前小时数表示为已使用的小时数与允许使用的小时数,这因客户而异,因此我无法输入整定值。因此,值=花费的小时数,范围为[0,允许的小时数]

我尝试过使用.iloc和.values,但它们都无法将整数单独作为自变量使用。然而,我也有一种感觉,我把仪表盘搞砸了,所以如果有人能帮我把它拧松,这样我就能在周五之前拿到它,那就太好了

编辑

@mozway,很抱歉(显然也是这样)。csv如下所示:

    Client | Hours Spent | Hours Allowed | Last Updated
     XXXX  |     30.81   |          60   |  2021-09-07

等等。至于精确定位,它给了我一个错误的指示数字


    elif client != "All":
    dff = dfhours.query('Client == "{}"'.format(client))
    ha = dff.values[0][5]
        
    fig = go.Figure(go.Indicator(
        domain = {'x': [0, 1], 'y': [0, 1]},
        value = dff['Hours Spent'],
        mode = "gauge+number",
        gauge = {'axis': {'range':[None, ha]}}))
    
    ValueError: 
        Invalid value of type 'pandas.core.series.Series' received
    for the 'value' property of indicator
    Received value: 0    30.81
    Name: Hours Spent, dtype: float64
    
    The 'value' property is a number and may be specified as:
      - An int or float

它应该使用花费的小时数作为仪表的值,允许的小时数作为仪表的结束

结束编辑


    

    app = dash.Dash(__name__)
    
        dfhours = pd.read_csv("hothours9-7.csv")
        dfhours['Last Updated'] = pd.to_datetime(dfhours['Last Updated'])
    dfclients = pd.read_csv("hotclients9-7.csv")
    clients = clientlist['Client'].unique()
    
    app.layout = html.Div(children=[
        html.H1(
            children='Hello!',
            style={
                'textAlign': 'center'
            }
        ),
        
        html.Br(),
        
        html.Div([
            html.Label('Clients'),
            dcc.Dropdown(
                id='clients-list',
                options=[{'label': i, 'value': i} for i in clients],
                value='All',
                style = {'width': "80%"}
            ),
            dcc.Dropdown(
                id='info-drop',
                options = [{'label': i, 'value': i} for i in ['Historical Hours', 'Current Hours']],
                value = 'Current Hours',
            )
        ]),
        html.Br(),
        
       dcc.Graph(id='info-graph')         
    ])
    
    
    #-------------------------------------------
    
    @app.callback( 
                Output('info-graph','figure'),
                [Input('clients-list','value'),
                 Input('info-drop','value')])
    def update_graph(client,info):    
        if info == "Current Hours":
            if client == "All":
                fig = px.bar(dfhours, x="Client", y="Hours Spent")
            
            elif client != "All":
                dff = dfhours.query('Client == "{}"'.format(client))
                ha = dff.values[0][5]
            
                fig = go.Figure(go.Indicator(
                    domain = {'x': [0, 1], 'y': [0, 1]},
                    value = dff['Hours Spent'],
                    mode = "gauge+number",
                    gauge = {'axis': {'range':[None, ha]}}))
        elif info == 'Historical Hours':
            if client == "All":
                dcc.Checklist(
                    options = [{"label": x, "value": x} for x in dfclients['Client']]),
                fig = px.line(dfclients,x="Last Updated",y="Hours Spent",color="Client")
            
            elif client != "All":
                dff = dfclients.query('Client == "{}"'.format(client)),
                
                fig = px.line(dff, x="Last Updated",y="Hours Spent")
        return fig
    
    
    
    if __name__=='__main__':
        app.run_server(debug=False)


Tags: csvinfoclientvaluehtmlfigalllast
1条回答
网友
1楼 · 发布于 2024-06-02 05:36:25
  • 已经模拟了你的数据
  • 过滤数据帧后的reset_index()的简单情况允许您始终以索引0的形式访问行(假设每个客户端一行)
  • 已经使用了dash1.0.0,因此htmldcc包不是导入的,而是引用的
  • 您在回调中构建了检查表,该检查表在任何地方都不会使用
from jupyter_dash import JupyterDash
import dash
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go

# app = dash.Dash(__name__)
app = JupyterDash(__name__)

# dfhours = pd.read_csv("hothours9-7.csv")
# dfhours['Last Updated'] = pd.to_datetime(dfhours['Last Updated'])
# dfclients = pd.read_csv("hotclients9-7.csv")
# simulate data...
h = np.random.uniform(10, 40, 4)
dfhours = pd.DataFrame(
    {
        "Client": list("ABCD"),
        "Hours Spent": h,
        "Hours Allowed": h * np.random.uniform(1.5, 2, 4),
    }
)
clientlist = pd.DataFrame({"Client": list("ABCD")})
clients = clientlist["Client"].unique()
dfclients = pd.DataFrame(
    {
        "Last Updated": pd.date_range("1-May-2021", periods=60),
        "Client": np.random.choice(list("ABCD"), 60),
        "Hours Spent": np.random.uniform(10, 40, 60),
    }
)

app.layout = dash.html.Div(
    children=[
        dash.html.H1(children="Hello!", style={"textAlign": "center"}),
        dash.html.Br(),
        dash.html.Div(
            [
                dash.html.Label("Clients"),
                dash.dcc.Dropdown(
                    id="clients-list",
                    options=[{"label": i, "value": i} for i in clients],
                    value="All",
                    style={"width": "80%"},
                ),
                dash.dcc.Dropdown(
                    id="info-drop",
                    options=[
                        {"label": i, "value": i}
                        for i in ["Historical Hours", "Current Hours"]
                    ],
                    value="Current Hours",
                ),
            ]
        ),
        dash.html.Br(),
        dash.dcc.Graph(id="info-graph"),
    ]
)


#                      -


@app.callback(
    Output("info-graph", "figure"),
    [Input("clients-list", "value"), Input("info-drop", "value")],
)
def update_graph(client, info):
    if info == "Current Hours":
        if client == "All":
            fig = px.bar(dfhours, x="Client", y="Hours Spent")

        elif client != "All":
            dff = dfhours.loc[dfhours["Client"].eq(client)].reset_index(drop=True)

            fig = go.Figure(
                go.Indicator(
                    domain={"x": [0, 1], "y": [0, 1]},
                    value=dff.loc[0, "Hours Spent"],
                    mode="gauge+number",
                    gauge={"axis": {"range": [0, dff.loc[0, "Hours Allowed"]]}},
                )
            )
    elif info == "Historical Hours":
        if client == "All":
            # this is spurious !!!
            dash.dcc.Checklist(
                options=[{"label": x, "value": x} for x in dfclients["Client"]]
            ),
            fig = px.line(dfclients, x="Last Updated", y="Hours Spent", color="Client")

        elif client != "All":
            dff = dfclients.query('Client == "{}"'.format(client))
            fig = px.line(dff, x="Last Updated", y="Hours Spent")
    return fig


if __name__ == "__main__":
    #     app.run_server(debug=False)
    app.run_server(mode="inline")

相关问题 更多 >