面试题答案
一键面试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
库创建了一个交互式散点图,满足题目要求:
- 散点图展示了
x
和y
列表中的数据点。 - 鼠标悬停在散点上时,显示点的坐标信息。
- 通过下拉菜单,可以切换散点的颜色模式(红色和蓝色)。