首页 > 解决方案 > 始终在散点图上显示轨迹名称,无需将鼠标悬停在其上

问题描述

我试图弄清楚是否有一种方法可以让 Python plotly scatterpolar 轨迹的名称始终可见,而不必将鼠标悬停在图表上的每个轨迹上。这就是我迄今为止在代码方面所拥有的。

import plotly.graph_objects as go

categories = ['Passing', 'Dribbling', 'Shooting', 'Defense', 'Fitness']

fig = go.Figure()

fig.add_traces(go.Scatterpolar(
    r=[6.33, 3.71, 0, 5.45, 5],
    theta=categories,
    fill='toself',
    name='Team Average'
))

fig.add_traces(go.Scatterpolar(
    r=[9.38, 2.86, 0, 5.0, 5.6],
    theta=categories,
    fill='toself',
    name='Player Average'
))

fig.update_layout(
    polar=dict(
        radialaxis=dict(
            visible=False,
            range=[0,10]
        )
    ),
    showlegend=False
)

fig.show()

这就是我运行当前散点图时的样子。如您所见,它没有显示每条痕迹的名称,只有当我将鼠标悬停在每条痕迹上时才会出现。

标签: pythonplotly

解决方案


对于go.Scatterpolar图表,文本注释很困难,因为您需要为文本注释指定笛卡尔 x 和 y 坐标。图表内文本注释的极坐标尚不可用,至少根据链接的 Plotly 论坛帖子。虽然您可以将每个点的极坐标转换为 x 和 y 坐标,然后在每个位置添加文本,但这似乎是一个笨拙的解决方案,除非确实有必要。

一种折衷方案是用于px.line_polar绘制图表,并使用text参数指定为每个点添加的文本。不幸的是,您只能从数据中选择一个字段(在您的情况下,您可以选择显示传递给 parameter 的值r,或传递给 parameter 的类别theta)。

要使 px.line_polar 看起来像 go.Scatterpolar,您需要在线条之间添加填充。此外,要在第一个之上添加第二个 px.line_polar 图表,您需要创建一个新图形,然后将该图形的数据添加为轨迹。您还需要手动指定第二个 px.line_polar 图表的颜色。

import plotly.express as px
import plotly.graph_objects as go

categories = ['Passing', 'Dribbling', 'Shooting', 'Defense', 'Fitness']

fig = go.Figure()

fig = px.line_polar(
    {'Team Average':[6.33, 3.71, 0, 5.45, 5], 'direction':categories}, 
    r="Team Average", 
    theta="direction", 
    start_angle=360,
    line_close=True,
    text="Team Average",
)

fig2 = px.line_polar(
    {'Player Average':[9.38, 2.86, 0, 5.0, 5.6], 'direction':categories}, 
    r="Player Average", 
    color_discrete_sequence=["salmon"]*5,
    theta="direction",
    start_angle=360, 
    line_close=True,
    text="Player Average",
)

## add fig2 to fig
fig.add_trace(fig2.data[0])

fig.update_traces(textposition='top center', fill='toself')

fig.update_layout(
    polar=dict(
        radialaxis=dict(
            visible=False,
            range=[0,10]
        )
    ),
    showlegend=False
)

fig.show()

在此处输入图像描述


推荐阅读