带有线图的破折号下拉菜单

时间:2020-07-12 14:05:31

标签: python pandas plotly plotly-dash

我正在尝试将破折号中的下拉列表与数字连接起来。我正在使用以下代码:

df = pd.read_csv('https://api.statbank.dk/v1/data/mpk100/CSV?valuePresentation=Value&timeOrder=Ascending&LAND=*&Tid=*', sep=';')
df = df[df['INDHOLD'] != '..']
df['rate'] = df['INDHOLD'].str.replace(',', '.').astype(float)
df_countries = df['LAND'].unique()

df['TID'] = pd.to_datetime(df['TID']) #datetime
df.groupby('LAND')

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = JupyterDash(__name__, external_stylesheets=external_stylesheets)

# Create server variable with Flask server object for use with gunicorn
server = app.server

app.layout = html.Div([

    html.Div([
        html.Div([
            dcc.Dropdown(id='linedropdown',
                options=[{'label': i, 'value': i} for i in df_countries],                    
                value='DANMARK',
                multi=True,
                clearable=False
            ),
        ],className='six columns'),

    ],className='row'),

    html.Div([
        html.Div([
            dcc.Graph(id='linechart'),
        ],className='six columns'),
    ],className='row'),
])

@app.callback(
    [Output('linechart', 'figure')],
    [Input('linedropdown', 'value')]
)

def update_graph(linedropval):
 
    df_filterd = df[df['LAND'].isin(['INDHOLD'])]
     #extract list of chosen countries
    list_chosen_countries=df_filterd['LAND'].tolist()
    #filter original df according to chosen countries
    #because original df has all the complete dates
    df_line = df[df['LAND'].isin(list_chosen_countries)]

    
    line_chart = px.line(
            data_frame=df_line,
            x='TID',
            y=linedropval,
            color='LAND',
            labels={'Rate':'rate', 'Datetime':'date'},
            )
    line_chart.update_layout(uirevision='foo')

    return (line_chart)

#------------------------------------------------------------------
app.run_server()

但是我在仪表板中遇到以下错误:

ValueError: All arguments should have the same length. The length of 

column argument `df[color]` is 0, whereas the length of  previously-

processed arguments ['TID', 'y'] is 1

ValueError: Value of 'y' is not the name of a column in 'data_frame'. 
Expected one of ['LAND', 'TID', 'INDHOLD', 'rate'] but received: DANMARK

我该如何解决?下拉列表中包括多年来享有尊重利率的国家。这应该很简单。但是我在回调中遇到问题。

1 个答案:

答案 0 :(得分:0)

数据框中的所有列都是大写的:

Index(['LAND', 'TID', 'INDHOLD', 'rate'], dtype='object')

'LAND'列中的所有字符串都是大小写混合的:

array(['Belgien', 'Bulgarien', 'Danmark', 'Estland', 'Finland',
       'Frankrig', 'Grækenland', 'Irland', 'Island', 'Italien', 'Letland',
       'Litauen', 'Luxembourg', 'Nederlandene', 'Norge', 'Polen',
       'Portugal', 'Rumænien', 'Rusland', 'Schweiz', 'Slovakiet',
       'Slovenien', 'Spanien', 'Storbritannien', 'Sverige', 'Tjekkiet',
       'Tyskland', 'Ungarn', 'Østrig', 'Sydafrika', 'Canada', 'Mexico',
       'USA', 'Israel', 'Indien', 'Japan', 'Sydkorea', 'Tyrkiet',
       'Australien', 'New Zealand', 'Euro-dollar-renten'], dtype=object)

您正在尝试仅使用'DANMARK'之类的大写字母来引用所有国家/地区。 进行更正后,将使用有效的选择器启动该应用。由于您的过滤有点怪异,因此该数字并不太有效。让我知道您要在这里实现什么,我们也可以看看。

人物/应用

enter image description here

完整代码:

import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

df = pd.read_csv('https://api.statbank.dk/v1/data/mpk100/CSV?valuePresentation=Value&timeOrder=Ascending&LAND=*&Tid=*', sep=';')
df = df[df['INDHOLD'] != '..']
df['rate'] = df['INDHOLD'].str.replace(',', '.').astype(float)
df_countries = df['LAND'].unique()

df['TID'] = pd.to_datetime(df['TID']) #datetime
df.groupby('LAND')

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = JupyterDash(__name__, external_stylesheets=external_stylesheets)

# Create server variable with Flask server object for use with gunicorn
server = app.server

app.layout = html.Div([

    html.Div([
        html.Div([
            dcc.Dropdown(id='linedropdown',
                options=[{'label': i, 'value': i} for i in df_countries],                    
                value='Danmark',
                multi=True,
                clearable=False
            ),
        ],className='six columns'),

    ],className='row'),

    html.Div([
        html.Div([
            dcc.Graph(id='linechart'),
        ],className='six columns'),
    ],className='row'),
])

@app.callback(
    [Output('linechart', 'figure')],
    [Input('linedropdown', 'value')]
)

def update_graph(linedropval):
    #global df_filtered
    global df_line
    df_filtered = df[df['LAND'].isin(['INDHOLD'])]
     #extract list of chosen countries
    list_chosen_countries=df_filterd['LAND'].tolist()
    #filter original df according to chosen countries
    #because original df has all the complete dates
    df_line = df[df['LAND'].isin(list_chosen_countries)]

    
    line_chart = px.line(
            data_frame=df_line,
            x='TID',
            y=linedropval,
            color='LAND',
            labels={'Rate':'rate', 'Datetime':'date'},
            )
    line_chart.update_layout(uirevision='foo')

    return (line_chart)

#------------------------------------------------------------------


# Run app and display result inline in the notebook
app.enable_dev_tools(dev_tools_hot_reload =True)
app.run_server(mode='inline', port = 8040, dev_tools_ui=True, debug=True,
              dev_tools_hot_reload =True, threaded=True)