matplotlib在散点p中不显示图例

2024-04-25 18:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

%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.

enter image description here

它给我看了一个情节,但没有告诉我传说。它也不会给我错误。在

我做错什么了吗?在


Tags: importdataframedfmatplotlibas绘制inlineplt
1条回答
网友
1楼 · 发布于 2024-04-25 18:26:13

编辑:

生成一些随机数据:

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

绘图:

^{pr2}$

结果:

enter image description here 说明:

不需要过多地研究matplotlib内部的细节,一次绘制一个集群就可以解决这个问题。 更具体地说,ax.scatter()返回一个PathCollection对象,我们在这里显式地丢弃了它,但它似乎在内部传递给某种图例处理程序。一次绘制所有簇只生成一个PathCollection/label对,而一次绘制一个簇生成n_clustersPathCollection/label对。您可以通过调用ax.get_legend_handles_labels()来查看这些对象,它返回如下内容:

([<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. 如果使用python2,请确保i/n_clustersfloat

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


旧的简单解决方案

如果您对colorbar(而不是离散值标签)没有问题,可以使用Pandas内置的Matplotlib功能:

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

enter image description here

相关问题 更多 >