如何在Plotly scatter3d 3D散点图中搜索指定数据点?
词向量3D散点图添加单词搜索功能的实现方法
方案一:结合Dash实现交互式搜索(Plotly场景)
如果你的3D散点图是用Plotly生成的,推荐用Dash添加搜索组件,步骤如下:
- 导入依赖库:
import dash from dash import dcc, html, Input, Output import plotly.graph_objects as go - 初始化Dash应用并构建布局,加入搜索框和已有的3D图表:
app = dash.Dash(__name__) # 假设your_existing_fig是你已经生成的3D散点图对象,words_list是所有单词的列表 app.layout = html.Div([ dcc.Input( id='word-search-input', type='text', placeholder='输入单词搜索...', style={'width': '300px', 'margin': '10px'} ), dcc.Graph(id='3d-word-vec-plot', figure=your_existing_fig) ]) - 添加回调函数,实现输入搜索时高亮匹配的点:
@app.callback( Output('3d-word-vec-plot', 'figure'), Input('word-search-input', 'value') ) def highlight_matching_words(search_term): fig = your_existing_fig.copy() if not search_term: # 无输入时恢复默认样式 fig.data[0].marker.color = 'lightblue' fig.data[0].marker.size = 5 return fig # 匹配包含搜索词的单词(不区分大小写) match_indices = [ i for i, word in enumerate(words_list) if search_term.lower() in word.lower() ] # 设置样式:匹配点高亮,其余默认 fig.data[0].marker.color = [ 'crimson' if i in match_indices else 'lightblue' for i in range(len(words_list)) ] fig.data[0].marker.size = [ 10 if i in match_indices else 5 for i in range(len(words_list)) ] return fig if __name__ == '__main__': app.run_server(debug=True)
运行后打开本地服务器地址,就能在搜索框输入单词,实时高亮匹配的散点。
方案二:纯前端HTML+JS实现(无需后端)
如果不想引入Dash,可以把Plotly图表导出为HTML后,添加前端搜索功能:
- 先把图表保存为HTML:
your_existing_fig.write_html('word_vector_3d.html') - 打开生成的HTML文件,在
<body>开头添加搜索框:<input type="text" id="wordSearch" placeholder="搜索单词..." style="padding: 8px; margin: 10px;"> - 在HTML的
<script>标签末尾添加以下JS代码,监听输入并修改点的样式:document.getElementById('wordSearch').addEventListener('input', function(e) { const searchText = e.target.value.toLowerCase(); // 获取所有散点元素 const scatterPoints = document.querySelectorAll('.scatterpoint'); scatterPoints.forEach((point, index) => { // 从点的data-text属性获取对应单词(Plotly会自动把hover文本存在这里) const word = point.getAttribute('data-text').toLowerCase(); if (searchText && word.includes(searchText)) { point.style.fill = 'crimson'; point.setAttribute('r', '8'); } else { point.style.fill = 'lightblue'; point.setAttribute('r', '4'); } }); });
打开修改后的HTML文件,就能使用搜索框筛选高亮单词对应的点。
方案三:Python预处理快速定位(临时需求)
如果只是临时查找某个特定单词,直接在Python中过滤标记后重新绘图即可:
# 假设words_list是单词列表,your_existing_fig是已生成的图表 target_word = '你要搜索的单词' if target_word in words_list: target_idx = words_list.index(target_word) # 设置颜色和大小,高亮目标点 colors = ['lightblue'] * len(words_list) sizes = [5] * len(words_list) colors[target_idx] = 'crimson' sizes[target_idx] = 12 your_existing_fig.data[0].marker.color = colors your_existing_fig.data[0].marker.size = sizes your_existing_fig.show()
内容的提问来源于stack exchange,提问作者Atirag
相关产品推荐
相关产品推荐

