Python 为散点图添加图例

Python 为散点图添加图例,python,matplotlib,legend,data-science,scatter-plot,Python,Matplotlib,Legend,Data Science,Scatter Plot,下面是散点图的代码 for_tsne = np.hstack((X_embedding, y.values.reshape(-1,1))) for_tsne_df = pd.DataFrame(data=for_tsne, columns= ['Dimension_x','Dimension_y','Labels']) colors = {0:'red', 1:'blue', 2:'yellow'} #colors = ['red','blue'

下面是散点图的代码

  for_tsne = np.hstack((X_embedding, y.values.reshape(-1,1)))
  for_tsne_df = pd.DataFrame(data=for_tsne, columns= 
                ['Dimension_x','Dimension_y','Labels'])
  colors = {0:'red', 1:'blue', 2:'yellow'}
  #colors = ['red','blue']
  plt.scatter(for_tsne_df['Dimension_x'], 
  for_tsne_df['Dimension_y'],c=for_tsne_df['Labels'].apply(lambda x: 
                               colors[x]))
  plt.title("TSNE with BOW encoding of project_title")
  plt.xlabel("Dimension_x")
  plt.ylabel("Dimension_y")
  plt.legend()
  plt.show()`

如何添加图例?上面的代码仅显示一个标签作为
Dimension\u y

一个选项是将标签分配给
plt.scatter()
。只有使用标签打印数据时,图例才会出现:

  for_tsne = np.hstack((X_embedding, y.values.reshape(-1,1)))
  for_tsne_df = pd.DataFrame(data=for_tsne, columns= 
                ['Dimension_x','Dimension_y','Labels'])
  colors = {0:'red', 1:'blue', 2:'yellow'}
  #colors = ['red','blue']
  plt.scatter(for_tsne_df['Dimension_x'], 
  for_tsne_df['Dimension_y'],c=for_tsne_df['Labels'].apply(lambda x: 
                               colors[x]))
  plt.title("TSNE with BOW encoding of project_title")
  plt.xlabel("Dimension_x")
  plt.ylabel("Dimension_y")
  plt.legend()
  plt.show()`
import matplotlib.pyplot as plt
import numpy as np

x = np.random.random(size=(100))
y = np.random.random(size=(100))
x1 = np.random.random(size=(100))
y1 = np.random.random(size=(100))

plt.scatter(x,y, label='sample 1')
plt.scatter(x1,y1, label='sample 2')
plt.title("TSNE with BOW encoding of project_title")
plt.xlabel("Dimension_x")
plt.ylabel("Dimension_y")
plt.legend()
plt.show()

参见示例。
  for_tsne = np.hstack((X_embedding, y.values.reshape(-1,1)))
  for_tsne_df = pd.DataFrame(data=for_tsne, columns= 
                ['Dimension_x','Dimension_y','Labels'])
  colors = {0:'red', 1:'blue', 2:'yellow'}
  #colors = ['red','blue']
  plt.scatter(for_tsne_df['Dimension_x'], 
  for_tsne_df['Dimension_y'],c=for_tsne_df['Labels'].apply(lambda x: 
                               colors[x]))
  plt.title("TSNE with BOW encoding of project_title")
  plt.xlabel("Dimension_x")
  plt.ylabel("Dimension_y")
  plt.legend()
  plt.show()`