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

问题描述

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

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)

现在,我的“标签”包含以下内容:

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]

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

#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)

标签: pythonpython-3.xdataframedrop-down-menuplotly

解决方案


一个好的起点是Dropdown Menus 的 Plotly 文档。这绝不是一个完整的答案,但是从这个 Plotly 社区论坛答案中大量借鉴,我们可以NaN从您的列中删除,并为您的菜单创建一个按钮列表。

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

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()

在此处输入图像描述


推荐阅读