MST

星途 面试题库

面试题:Python中Plotly交互式散点图及联动功能实现

给定两个列表x = [1, 2, 3, 4, 5]和y = [5, 4, 6, 2, 7],使用Plotly创建一个交互式散点图。当鼠标悬停在散点上时,显示点的坐标信息。并且,创建一个下拉菜单,通过选择不同选项,可以切换散点的颜色模式(例如从红色到蓝色)。
18.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import plotly.graph_objects as go

x = [1, 2, 3, 4, 5]
y = [5, 4, 6, 2, 7]

fig = go.Figure()

# 添加散点
fig.add_trace(go.Scatter(
    x=x,
    y=y,
    mode='markers',
    marker=dict(
        color='red',
        size=10
    ),
    hovertext=[f'x: {xi}, y: {yi}' for xi, yi in zip(x, y)],
    hoverinfo='text'
))

# 创建下拉菜单
dropdown = [
    {
        'active': 0,
        'buttons': [
            {
                'label': '红色',
                'method': 'update',
                'args': [
                    {'marker.color': ['red'] * len(x)}
                ]
            },
            {
                'label': '蓝色',
                'method': 'update',
                'args': [
                    {'marker.color': ['blue'] * len(x)}
                ]
            }
        ]
    }
]

fig.update_layout(
    updatemenus=dropdown
)

fig.show()

上述代码使用Plotly库创建了一个交互式散点图,满足题目要求:

  1. 散点图展示了xy列表中的数据点。
  2. 鼠标悬停在散点上时,显示点的坐标信息。
  3. 通过下拉菜单,可以切换散点的颜色模式(红色和蓝色)。