matplotlib 在散点图中不显示图例

matplotlib does not show legend in scatter plot

我正在尝试解决聚类问题,我需要为我的聚类绘制散点图。

%matplotlib inline
import matplotlib.pyplot as plt
df = pd.merge(dataframe,actual_cluster)
plt.scatter(df['x'], df['y'], c=df['cluster'])
plt.legend()
plt.show()

df['cluster'] is the actual cluster number. So I want that to be my color code.

它给我展示了一个情节,但没有给我展示传说。它也不给我错误。

我是不是做错了什么?

编辑:

正在生成一些随机数据:

from scipy.cluster.vq import kmeans2
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

n_clusters = 10
df = pd.DataFrame({'x':np.random.randn(1000), 'y':np.random.randn(1000)})
_, df['cluster'] = kmeans2(df, n_clusters)

更新

  • 使用 seaborn.relplotkind='scatter' 或使用 seaborn.scatterplot
    • 指定 hue='cluster'
# figure level plot
sns.relplot(data=df, x='x', y='y', hue='cluster', palette='tab10', kind='scatter')

# axes level plot
fig, axes = plt.subplots(figsize=(6, 6))
sns.scatterplot(data=df, x='x', y='y', hue='cluster', palette='tab10', ax=axes)
axes.legend(loc='center left', bbox_to_anchor=(1, 0.5))

原答案

绘图(matplotlib v3.3.4):

fig, ax = plt.subplots(figsize=(8, 6))
cmap = plt.cm.get_cmap('jet')
for i, cluster in df.groupby('cluster'):
    _ = ax.scatter(cluster['x'], cluster['y'], color=cmap(i/n_clusters), label=i, ec='k')
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

结果:

解释:

不要过多关注 matplotlib 内部的细节,一次绘制一个集群可以解决问题。 更具体地说,ax.scatter() returns 我们在这里明确丢弃的 PathCollection 对象,但 似乎 在内部传递给某种图例处理程序.一次绘制全部只生成一个 PathCollection/标签对,而一次绘制一个集群生成 n_clusters PathCollection/标签对。您可以通过调用 ax.get_legend_handles_labels() which returns 来查看这些对象,例如:

([<matplotlib.collections.PathCollection at 0x7f60c2ff2ac8>,
  <matplotlib.collections.PathCollection at 0x7f60c2ff9d68>,
  <matplotlib.collections.PathCollection at 0x7f60c2ff9390>,
  <matplotlib.collections.PathCollection at 0x7f60c2f802e8>,
  <matplotlib.collections.PathCollection at 0x7f60c2f809b0>,
  <matplotlib.collections.PathCollection at 0x7f60c2ff9908>,
  <matplotlib.collections.PathCollection at 0x7f60c2f85668>,
  <matplotlib.collections.PathCollection at 0x7f60c2f8cc88>,
  <matplotlib.collections.PathCollection at 0x7f60c2f8c748>,
  <matplotlib.collections.PathCollection at 0x7f60c2f92d30>],
 ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])

所以实际上 ax.legend() 等同于 ax.legend(*ax.get_legend_handles_labels()).

备注:

  1. 如果使用 Python 2,确保 i/n_clustersfloat

  2. 省略 fig, ax = plt.subplots() 并使用 plt.<method> 代替 ax.<method> 的工作正常,但我总是更喜欢明确 指定我正在使用的 Axes 对象,而不是隐式使用 “当前轴”(plt.gca()).


旧的简单解决方案

如果您可以使用颜色条(而不是离散值标签),则可以使用 Pandas 内置的 Matplotlib 功能:

df.plot.scatter('x', 'y', c='cluster', cmap='jet')

这是一个困扰我很久的问题。现在,我想提供另一个简单的解决方案。我们不必编写任何循环!!!

def vis(ax, df, label, title="visualization"):
    points = ax.scatter(df[:, 0], df[:, 1], c=label, label=label, alpha=0.7)
    ax.set_title(title)
    ax.legend(*points.legend_elements(), title="Classes")