我们如何将数据框中的字段添加到下拉控件中以在网页中绘制数据?

How can we add fields from a dataframe into a drop down control to plot data in a web page?

我有这段代码,可以很好地在网页中绘制图表。

import requests
import pandas as pd
from pandas import DataFrame
pd.set_option('display.max_columns', None)

url = 'https://www.federalreserve.gov/releases/h8/current/default.htm'
html = requests.get(url).content
df_list = pd.read_html(html)
df = df_list[10]

df = df.drop(df.columns[0], axis=1) #drop the first column 0,1,2 etc
df.columns = df.columns.droplevel(0) #remove the upper level of multi Index
df.rename(columns = {'Account.1':'Account'}, inplace = True) #Rename Columns
df = df.set_index('Account').transpose() #Transpose the data
#df.to_csv('C:\Users\ryans\OneDrive\Desktop\out.csv')
    

#Plot
import plotly.express as px
from plotly.offline import plot
fig = px.bar(df, x=df.index, y='Commercial and industrial loans',
            hover_data=['Commercial and industrial loans'], color='Commercial and industrial loans',
            labels={'Commercial and industrial loans'}, height=400)
plot(fig)

我可以使用下面的代码轻松地从数据框中获取列名。

#list(df)
labels = pd.DataFrame(columns=df.columns)

现在,我的 'labels' 包含这个:

Columns: [Assets, Bank credit, Securities in bank credit 2, Treasury and agency securities 3, Mortgage-backed securities (MBS) 4, Non-MBS 5, Other securities, Mortgage-backed securities (MBS) 6, Non-MBS 7, Loans and leases in bank credit 8, Commercial and industrial loans, Real estate loans, Residential real estate loans, Revolving home equity loans, Closed-end residential loans 9, Commercial real estate loans, Construction and land development loans 10, Secured by farmland 11, Secured by multifamily properties 12, Secured by nonfarm nonresidential properties 13, Consumer loans, Credit cards and other revolving plans, Other consumer loans, Automobile loans 14, All other consumer loans 15, All other loans and leases, Loans to nondepository financial institutions 16, All loans not elsewhere classified 17, LESS: Allowance for loan and lease losses, Cash assets 18, Total federal funds sold and reverse RPs 19, Loans to commercial banks 20, Other assets including trading assets 21, Total assets, nan, Liabilities, Deposits, Large time deposits, Other deposits, Borrowings, Net due to related foreign offices, Other liabilities including trading liabilities 22, Total liabilities, Residual (Assets LESS Liabilities) 23, nan, Memoranda, Net unrealized gains (losses) on available-for-sale securities 24, U.S. Treasury and agency securities, MBS 25]

所以,现在,我正在尝试向网页添加一个下拉控件,并让用户根据从下拉控件中选择的内容动态地在图表中绘制数据。我稍微修改了绘图代码,如下所示,但我不知道如何将 'labels' 数据输入下拉控件。

#Plot
import plotly.express as px
from plotly.offline import plot
fig = px.bar(df, x=df.index, y=labels,
            hover_data=labels, color=labels,
            labels={labels}, height=400)
plot(fig)

Plotly documentation for Dropdown Menus. This is by no means a complete answer, but borrowing heavily from this Plotly Community Forum answer 是一个不错的起点,我们可以从您的列中删除 NaN,然后为您的菜单创建一个按钮列表。

您可能想要添加的一些内容(以及我会在时间允许时研究的内容):(1) 使条形图具有不同的颜色,(2) 更新 y-axis 标题以匹配列姓名

import requests
import pandas as pd
from pandas import DataFrame
pd.set_option('display.max_columns', None)

url = 'https://www.federalreserve.gov/releases/h8/current/default.htm'
html = requests.get(url).content
df_list = pd.read_html(html)
df = df_list[10]

df = df.drop(df.columns[0], axis=1) #drop the first column 0,1,2 etc
df.columns = df.columns.droplevel(0) #remove the upper level of multi Index
df.rename(columns = {'Account.1':'Account'}, inplace = True) #Rename Columns
df = df.set_index('Account').transpose() #Transpose the data
#df.to_csv('C:\Users\ryans\OneDrive\Desktop\out.csv')
    

#Plot
import plotly.graph_objects as go
import plotly.express as px
from plotly.offline import plot


fig = px.bar(df, x=df.index, height=400)
# plot(fig)

buttonlist = []
for label in df.columns.dropna():
    buttonlist.append(
        dict(
            args=['y',[df[str(label)]]],
            label=str(label),
            method='restyle'
        )
    )

fig.update_layout(
    # Add dropdown
    updatemenus=[
        go.layout.Updatemenu(
            buttons=buttonlist,
            direction="down",
            pad={"r": 10, "t": 10},
            showactive=True,
            x=0.1,
            xanchor="left",
            y=1.1,
            yanchor="top"
        ),
    ],
    autosize=True,
    yaxis={'title':'Value'},
)

fig.show()