【问题标题】:How to label these points on the scatter plot如何在散点图上标记这些点
【发布时间】:2020-11-15 15:15:37
【问题描述】:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
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]))
plt.show()

Got the plot but not able to label these points

【问题讨论】:

  • 您要标记这些点中的每一个,还是只标记特定点?
  • @ChaddRobertson 每一点

标签: python pandas matplotlib scatter-plot


【解决方案1】:

如果您想标记每个点,您可以遍历绘制的每个坐标,在绘制点的位置使用 plt.text() 为其分配一个标签,如下所示:

from matplotlib import pyplot as plt

y_points = [i for i in range(0, 20)]
x_points = [(i*3) for i in y_points]

offset = 5

plt.figure()
plt.grid(True)
plt.scatter(x_points, y_points)

for i in range(0, len(x_points)):
    plt.text(x_points[i] - offset, y_points[i], f'{x_points[i]}')
    
plt.show()

在上面的例子中,它将给出以下内容:

偏移只是为了让标签更易读,这样它们就不会在散点的顶部。

显然我们无权访问您的电子表格,但同样的基本概念也适用。

编辑

对于非数值,您可以简单地将字符串定义为坐标。可以这样做:

from matplotlib import pyplot as plt

y_strings = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
x_values = [i for i, string in enumerate(y_strings)]

# Plot coordinates:

plt.scatter(x_values, y_strings)

for i, string in enumerate(y_strings):
    plt.text(x_values[i], string, f'{x_values[i]}:{string}')

plt.grid(True)
plt.show()

这将提供以下输出:

【讨论】:

  • 我不能这样做,因为我的 y 轴是一个字符串,而 x 轴是整数。标签本身就是字符串。知道如何进行吗?
  • 是的,所以我是根据您的轴计算得出的。这是一个相当简单的修复——只需创建一个与“pos”列长度相同的数值列表(可以很好地使用enumerate() 代替上述循环中的range())。现在将其添加到我的答案中。
  • 在我做之前,每个 x值是否有对应的y字符串?
  • 是的,每个 x 值都有一个对应的 y 字符串
  • 很遗憾没用;发布了另一个关于相同的问题。你能帮我吗?
猜你喜欢
  • 2019-09-30
  • 2012-03-18
  • 2012-10-25
  • 1970-01-01
  • 2022-01-16
  • 2021-08-16
  • 1970-01-01
  • 2016-08-05
  • 2020-02-01
相关资源
最近更新 更多