2017-09-03 42 views
1

我花了几个小时试图完成我认为是一项简单的任务,即在使用seaborn的同时将标签添加到XY图上。在x中添加标签与seaborn的散点图

这里是我的代码

import seaborn as sns 
import matplotlib.pyplot as plt 
%matplotlib inline 

df_iris=sns.load_dataset("iris") 

sns.lmplot('sepal_length', # Horizontal axis 
      'sepal_width', # Vertical axis 
      data=df_iris, # Data source 
      fit_reg=False, # Don't fix a regression line 
      size = 8, 
      aspect =2) # size and dimension 

plt.title('Example Plot') 
# Set x-axis label 
plt.xlabel('Sepal Length') 
# Set y-axis label 
plt.ylabel('Sepal Width') 

我想添加到每个点在图上的文字在“种”栏。

我见过很多使用matplotlib但不使用seaborn的例子。

任何想法?谢谢。你可以这样做

+0

你能提供的示例数据帧? 'z'是否包含X轴和Y轴的标签信息?你想标注整个轴还是轴标记? Seaborn在引擎盖下使用了Matplotlib - 你是说你不想使用'plt'方法,而是'sns'方法来标记你的地块? –

+0

增加了样本数据集。对不起 –

回答

4

的一种方法如下:

import seaborn as sns 
import matplotlib.pyplot as plt 
import pandas as pd 
%matplotlib inline 

df_iris=sns.load_dataset("iris") 

ax = sns.lmplot('sepal_length', # Horizontal axis 
      'sepal_width', # Vertical axis 
      data=df_iris, # Data source 
      fit_reg=False, # Don't fix a regression line 
      size = 10, 
      aspect =2) # size and dimension 

plt.title('Example Plot') 
# Set x-axis label 
plt.xlabel('Sepal Length') 
# Set y-axis label 
plt.ylabel('Sepal Width') 


def label_point(x, y, val, ax): 
    a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1) 
    for i, point in a.iterrows(): 
     ax.text(point['x']+.02, point['y'], str(point['val'])) 

label_point(df_iris.sepal_length, df_iris.sepal_width, df_iris.species, plt.gca()) 

enter image description here

+0

谢谢斯科特。它确实有阴谋,但对我来说,绘制的字符串看起来很奇怪。每个点都说了以下内容:“物种:setosa,名称:3,dtype:object”任何想法如何解决? –

相关问题