如何为多加密货币折线图添加支持单选、多选的下拉选择菜单
加密货币走势折线图多选下拉功能实现方案
最优实现方案基于你已导入的Dash框架完成,无需引入额外依赖,直接复用你已写好的爬虫和数据拉取逻辑,仅需替换静态绘图部分为动态交互逻辑即可,完整实现如下:
完整可运行代码
from datetime import datetime, timedelta from pycoingecko import CoinGeckoAPI import pandas as pd import pandas_datareader as pdr import plotly.graph_objs as go import requests import lxml.html as lh import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output # 爬取加密货币列表 url = 'https://finance.yahoo.com/cryptocurrencies?count=100&offset=0' page = requests.get(url) doc = lh.fromstring(page.content) tr_elements = doc.xpath('//tr') col=[] i=0 # For each row, store each first element (header) and an empty list for t in tr_elements[0]: i+=1 name=t.text_content() col.append((name,[])) for j in range(1,len(tr_elements)): T=tr_elements[j] i=0 for t in T.iterchildren(): data=t.text_content() if i>0: try: data=int(data) except: pass col[i][1].append(data) i+=1 Dict={title:column for (title,column) in col} df=pd.DataFrame(Dict) crypto_df = df.set_index('Symbol') CRYPTOS = [] CURRENCY = 'USD' for x in crypto_df.index: x = x.split('-')[0] CRYPTOS.append(x) # 提前拉取所有加密货币的历史数据,避免每次选择重复请求 def getData(cryptocurrency): now = datetime.now() current_date = now.strftime("%Y-%m-%d") last_year_date = (now - timedelta(days=365)).strftime("%Y-%m-%d") start = pd.to_datetime(last_year_date) end = pd.to_datetime(current_date) data = pdr.get_data_yahoo(f'{cryptocurrency}-{CURRENCY}', start, end) return data crypto_data = {crypto:getData(crypto) for crypto in CRYPTOS} # 初始化Dash应用 app = dash.Dash(__name__) # 页面布局 app.layout = html.Div([ html.H1('加密货币价格走势图表'), # 支持多选的下拉菜单 dcc.Dropdown( id='crypto-select', options=[{"label": c, "value": c} for c in CRYPTOS], value=CRYPTOS[:3], # 默认选中前3个加密货币 multi=True, # 开启多选模式 placeholder="请选择要展示的加密货币" ), # 图表承载组件 dcc.Graph(id='crypto-graph') ]) # 回调函数:根据选中的加密货币动态生成图表 @app.callback( Output('crypto-graph', 'figure'), Input('crypto-select', 'value') ) def update_graph(selected_cryptos): # 处理未选中任何币种的情况 if not selected_cryptos: return go.Figure() fig = go.Figure() # 仅渲染选中的加密货币折线 for name in selected_cryptos: fig.add_trace( go.Scatter( x = crypto_data[name].index, y = crypto_data[name].Close, name = name, ) ) # 保留原有样式配置 fig.update_layout( title = 'Cryptocurrency Price Chart', xaxis_title = 'Date', yaxis_title = f'Closing price ({CURRENCY})', legend_title = 'Cryptocurrencies' ) fig.update_yaxes(type='log', tickprefix='$') return fig if __name__ == '__main__': app.run_server(debug=True)
使用说明
运行代码后打开浏览器访问http://127.0.0.1:8050即可使用:
- 单选:直接点击下拉菜单中对应币种即可切换
- 多选:按住Ctrl键点击下拉菜单中对应币种,可同时选中多个币种展示
核心优化点
- 复用你原有数据爬取逻辑,所有历史数据仅拉取一次,选择币种时无需重复请求接口,加载速度快
- 完全保留你原有图表的对数坐标轴、美元单位前缀、标题等配置,无需额外调整样式
- 原生支持全量25种加密货币的单选/多选切换,无性能问题
内容的提问来源于stack exchange,提问作者Rubberleg
相关产品推荐
相关产品推荐

