【问题标题】:How to annotate points in a scatterplot based on a pandas column?如何根据熊猫列注释散点图中的点?
【发布时间】:2021-02-27 09:47:47
【问题描述】:

想要'Age' 作为 x 轴,'Pos' 作为 y 轴,标签为 'Player' 名称。但是由于某种原因,无法标记点。

代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import adjustText as at



data = pd.read_excel("path to  the file")
fig, ax = plt.subplots()
fig.set_size_inches(7,3)

df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])

df.plot.scatter(x='Age',
                y='Pos',
                c='DarkBlue', xticks=([15,20,25,30,35,40]))

y = df.Player
texts = []
for i, txt in enumerate(y):
    plt.text()
at.adjust_text(texts, arrowprops=dict(arrowstyle="simple, head_width=0.25, tail_width=0.05", color='black', lw=0.5, alpha=0.5))

plt.show()

数据总结:

df.head()

             Player Pos  Age
0  Thibaut Courtois  GK   28
1     Karim Benzema  FW   32
2      Sergio Ramos  DF   34
3    Raphael Varane  DF   27
4       Luka Modric  MF   35

错误:

ConversionError:无法将值转换为轴单位:'GK'

这是到目前为止的情节;无法标记这些点:

编辑: 这就是我想要的,但最重要的是:

另外,谁能帮我重新排列 yaxis 上的标签。 比如,我想要 FW,MF,DF,GK 作为我的订单,但情节是 MF,DF,FW,GK。

谢谢。

【问题讨论】:

  • “标记这些点”是什么意思?你能指出结果应该是什么样子吗? |你可能想用数据创建一个minimum reproducible example,这样人们就可以实际运行你的代码
  • 您可以通过重新排序保存轴标签的列表来重新排序轴标签。因此,第一步是为三列中的每一列创建一个列表——这将使您更容易开始使用(和操作)数据。执行此操作,然后重新审视我之前帮助您解决的问题 - 如果您在那之后仍然遇到问题,请告诉我们。

标签: python pandas matplotlib scatter-plot


【解决方案1】:

here 描述了类似的解决方案。本质上,您想在散点图中标注点。

我已经删除了你的代码。请注意,您需要使用matplotlib(而不是pandas)绘制数据:df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])。这样就可以使用annotation()-方法了。

import matplotlib.pyplot as plt
import pandas as pd

# build data
data = [
['Thibaut Courtois', 'GK', 28],
['Karim Benzema', 'FW', 32],
['Sergio Ramos','DF', 34],
['Raphael Varane', 'DF', 27],
['Luka Modric', 'MF', 35],
]
# create pandas DataFrame
df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])


# open figure + axis
fig, ax = plt.subplots()
# plot
ax.scatter(x=df['Age'],y=df['Pos'],c='DarkBlue')
# set labels
ax.set_xlabel('Age')
ax.set_ylabel('Pos')

# annotate points in axis
for idx, row in df.iterrows():
    ax.annotate(row['Player'], (row['Age'], row['Pos']) )
# force matplotlib to draw the graph
plt.show()

这是您将得到的输出:

【讨论】:

  • 知道如何使标签不相互重叠吗?
  • 如果您希望标签不与它们的对应点重叠,请使用textcoords='offset points' 选项。看看docsadvanced annotation 的帮助也相当不错。我不确定,如果您的点非常接近并且标签会相互重叠,是否可以选择。然后,您可能希望在一小部分标签上使用箭头
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 2021-12-28
  • 2017-05-07
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多