2016-03-03 111 views
1

我有2个数据框,1个有训练数据,另一个有标签。训练数据中有6个特征/列,标签数据帧中有1列。我想在我的小平面网格中绘制6个图 - 所有这些都是散点图。所以功能1与标签,功能2与标签,功能3与标签,功能4与标签。如何绘制具有多个数据框的FacetGrid散点图?

有人可以告诉我如何做到这一点?

例如,使用这些采样数据帧

In [15]: training 
Out[15]: 
    feature1 feature2 feature3 feature4 feature5 feature6 
0   2   3   4   5   2   5 
1   5   4   2   5   6   2 

In [16]: labels 
Out[16]: 
    label 
0  34 
1  2 

这应该使6个单独的散点图,每2个数据点。

回答

2

Seaborn有一个很好的FacetGrid function.You可以合并你的两个dataframes环绕正常matplotlib.pyplot.scatter()的seaborn facetgrid

import pandas as pd 
import random 
import matplotlib.pyplot as plt 
import seaborn as sns 

#make a test dataframe 
features = {} 
for i in range(7): 
    features['feature%s'%i] = [random.random() for j in range(10)] 
f = pd.DataFrame(features) 
labels = pd.DataFrame({'label':[random.random() for j in range(10)]}) 

#unstack it so feature labels are now in a single column 
unstacked = pd.DataFrame(f.unstack()).reset_index() 
unstacked.columns = ['feature', 'feature_index', 'feature_value'] 
#merge them together to get the label value for each feature value 
plot_data = pd.merge(unstacked, labels, left_on = 'feature_index', right_index = True) 
#wrap a seaborn facetgrid 
kws = dict(s=50, linewidth=.5, edgecolor="w") 
g = sns.FacetGrid(plot_data, col="feature") 
g = (g.map(plt.scatter, "feature_value", "label", **kws)) 

enter image description here

+0

我喜欢你的答案,但有可能for循环中的一个小小的技术错误 - 对于我在范围(7)中......然后我再次用于“[random.random()for i in range(10)]”......也许应该更改为“j”什么的? –

+0

我想你会发现,如果你测试代码,它会得出随机生成的测试数据帧的预期结果;但我同意我的两次使用可能会有点混乱。 – Sam

+0

啊..我猜你正在使用Python 3?是的,Python版本2泄漏了控制变量。参考:http://stackoverflow.com/a/4199355/904032 ...我在版本2上运行它。 –