2016-03-03 113 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上運行它。 –