如何将文本标签添加到 Python 中的 Plotly 散点图?

How can I add text labels to a Plotly scatter plot in Python?

我试图在 Python 中的 Plotly 散点图中的数据点旁边添加文本标签,但出现错误。

我该怎么做?

这是我的数据框:

world_rank  university_name country teaching    international   research    citations   income  total_score num_students    student_staff_ratio international_students  female_male_ratio   year
0   1   Harvard University  United States of America    99.7    72.4    98.7    98.8    34.5    96.1    20,152  8.9 25% NaN 2011

这是我的代码片段:

citation = go.Scatter(
                    x = "World Rank" + timesData_df_top_50["world_rank"],  <--- error
                    y = "Citation" + timesData_df_top_50["citations"], <--- error
                    mode = "lines+markers",
                    name = "citations",
                    marker = dict(color = 'rgba(48, 217, 189, 1)'),
                    text= timesData_df_top_50["university_name"])

错误如下所示。

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

您可以在 text 属性中包含文本标签。要确保它们显示在散点图上,请设置 mode='lines+markers+text'。参见Plotly documentation on text and annotations。我在下面根据您的代码提供了一个示例。

import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame({'world_rank': [1, 2, 3, 4, 5],
                   'university_name': ['Harvard', 'MIT', 'Stanford', 'Cambridge', 'Oxford'],
                   'citations': [98.8, 98.7, 97.6, 97.5, 96]})

layout = dict(plot_bgcolor='white',
              margin=dict(t=20, l=20, r=20, b=20),
              xaxis=dict(title='World Rank',
                         range=[0.9, 5.5],
                         linecolor='#d9d9d9',
                         showgrid=False,
                         mirror=True),
              yaxis=dict(title='Citations',
                         range=[95.5, 99.5],
                         linecolor='#d9d9d9',
                         showgrid=False,
                         mirror=True))

data = go.Scatter(x=df['world_rank'],
                  y=df['citations'],
                  text=df['university_name'],
                  textposition='top right',
                  textfont=dict(color='#E58606'),
                  mode='lines+markers+text',
                  marker=dict(color='#5D69B1', size=8),
                  line=dict(color='#52BCA3', width=1, dash='dash'),
                  name='citations')

fig = go.Figure(data=data, layout=layout)

fig.show()