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

问题描述 投票:0回答:1

我正在尝试在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')
python plotly scatter
1个回答
1
投票
import plotly.graph_objects as go
import pandas as pd

timesData_df_top_50 = 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', xaxis=dict(title='World Rank', linecolor='#d9d9d9', mirror=True),
              yaxis=dict(title='Citations', linecolor='#d9d9d9', mirror=True))

data = go.Scatter(x=timesData_df_top_50['world_rank'],
                  y=timesData_df_top_50['citations'],
                  text=timesData_df_top_50['university_name'],
                  mode='lines+markers+text',
                  marker=dict(color='rgba(48, 217, 189, 1)'),
                  name='citations')

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

fig.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.