如何在叠加散点图上注释(标签)?

how to annotate (label) on the overlay scatterplot?

这是我的代码。我在第二个绘图标签上出错。如何包含两个相互重叠的散点图的标签。还有如何添加图例来指定绿色是“叶子”,红色是“水果”。 提前致谢。

import pandas as pd
import matplotlib.pyplot as plt

df = {'id': ['a','b', 'c', 'd'],
    'x1': [2,3,4,5],
    'y1': [2,6,7,2],
        'x2': [4, 5, 6, 7],
      'y2':[4,6,7,9]}
df = pd.DataFrame(df)

ax =df.plot.scatter('x1', 'y1', c='green')
for i, txt in enumerate(df.id):
    ax.annotate(txt, (df.x1.iat[i],df.y1.iat[i]))
ax =plt.scatter(df['x2'],df['y2'],c='red')
for i, txt in enumerate(df.id):
    ax.annotate(txt, (df.x2.iat[i],df.y2.iat[i]))
plt.show()

问题是当您调用 plt.scatter 时您重命名了 ax 变量。虽然 pandas df.plot.scatter 执行 return 创建绘图的 matplotlib Axes 实例,但原生 matplotlib plt.scatter 而不是 return 一个 PathCollection 实例。然后您尝试调用 ax.annotate,但 annotate 不是路径集合的有效方法。

从 matplotlib 创建轴更安全,然后您可以控制每个图的创建位置。

在这里,我假设您出于某种原因打算使用两种不同的散点方法,并展示如何控制它们出现在哪些轴上。

您没有准确说明您希望每个散点图出现的位置,因此这里有几个选项:

2 个单独的数字

假设您希望在单独的 Figure 个实例中显示两个散点图,您可以执行以下操作:

import pandas as pd
import matplotlib.pyplot as plt

df = {'id': ['a', 'b', 'c', 'd'],
      'x1': [2, 3, 4, 5],
      'y1': [2, 6, 7, 2],
      'x2': [4, 5, 6, 7],
      'y2': [4, 6, 7, 9]}
df = pd.DataFrame(df)

fig1, ax1 = plt.subplots()
df.plot.scatter('x1', 'y1', c='green', ax=ax1)
for i, txt in enumerate(df.id):
    ax1.annotate(txt, (df.x1.iat[i], df.y1.iat[i]))

fig2, ax2 = plt.subplots()
ax2.scatter(df['x2'], df['y2'], c='red')
for i, txt in enumerate(df.id):
    ax2.annotate(txt, (df.x2.iat[i], df.y2.iat[i]))

plt.show()

同一张图有 2 个子图

假设您想要在同一张图上绘制 2 个子图:

import pandas as pd
import matplotlib.pyplot as plt

df = {'id': ['a', 'b', 'c', 'd'],
      'x1': [2, 3, 4, 5],
      'y1': [2, 6, 7, 2],
      'x2': [4, 5, 6, 7],
      'y2': [4, 6, 7, 9]}
df = pd.DataFrame(df)

fig, (ax1, ax2) = plt.subplots(ncols=2)

df.plot.scatter('x1', 'y1', c='green', ax=ax1)
for i, txt in enumerate(df.id):
    ax1.annotate(txt, (df.x1.iat[i], df.y1.iat[i]))

ax2.scatter(df['x2'], df['y2'], c='red')
for i, txt in enumerate(df.id):
    ax2.annotate(txt, (df.x2.iat[i], df.y2.iat[i]))

plt.show()

两个散点图在同一个轴上

假设您希望两个散点图出现在同一个子图中,您可以:

import pandas as pd
import matplotlib.pyplot as plt

df = {'id': ['a', 'b', 'c', 'd'],
      'x1': [2, 3, 4, 5],
      'y1': [2, 6, 7, 2],
      'x2': [4, 5, 6, 7],
      'y2': [4, 6, 7, 9]}
df = pd.DataFrame(df)

fig, ax = plt.subplots()

df.plot.scatter('x1', 'y1', c='green', ax=ax)
for i, txt in enumerate(df.id):
    ax.annotate(txt, (df.x1.iat[i], df.y1.iat[i]))

ax.scatter(df['x2'], df['y2'], c='red')
for i, txt in enumerate(df.id):
    ax.annotate(txt, (df.x2.iat[i], df.y2.iat[i]))

plt.show()

图例

最后,回答你关于标记颜色的问题。您可以为每个散点图实例分配一个 label,例如:

df.plot.scatter('x1', 'y1', c='green', ax=ax, label='leaf')
ax.scatter(df['x2'], df['y2'], c='red', label='fruit')

并在给定的轴上生成图例:

ax.legend()