Skip to main content
 首页 » 编程设计

python之如何将数据从 np 矩阵加载到 seaborn

2025年05月04日53haluo1

我想用标签颜色构建自己的散点图矩阵。我喜欢这个例子:Scatterplot Matrix .

我有一个问题。我不明白,如何将数据从 numpy matrix 加载到 seaborn dataframe

data_resc = np.random.rand(150,2) 
 
sns.set() 
 
df = DataFrame(data_resc) 
sns.pairplot(df, hue="species", size=2.5) 
sns.plt.show() 

这段代码有错误:

Traceback (most recent call last): 
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:3687) 
  File "pandas\hashtable.pyx", line 381, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:7192) 
TypeError: an integer is required 
 
During handling of the above exception, another exception occurred: 
 
Traceback (most recent call last): 
  File "file.py", line 69, in <module> 
    main() 
  File "file.py", line 64, in main 
    sns.pairplot(df, hue="species", size=2.5) 
  File "C:\Python34\lib\site-packages\seaborn\linearmodels.py", line 1720, in pairplot 
    size=size, aspect=aspect, dropna=dropna, **grid_kws) 
  File "C:\Python34\lib\site-packages\seaborn\axisgrid.py", line 857, in __init__ 
    hue_names = np.unique(np.sort(data[hue])) 
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 1780, in __getitem__ 
    return self._getitem_column(key) 
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 1787, in _getitem_column 
    return self._get_item_cache(key) 
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1068, in _get_item_cache 
    values = self._data.get(item) 
  File "C:\Python34\lib\site-packages\pandas\core\internals.py", line 2849, in get 
    loc = self.items.get_loc(item) 
  File "C:\Python34\lib\site-packages\pandas\core\index.py", line 1402, in get_loc 
    return self._engine.get_loc(_values_from_object(key)) 
  File "pandas\index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas\index.c:3807) 
  File "pandas\index.pyx", line 156, in pandas.index.IndexEngine.get_loc (pandas\index.c:3744) 
KeyError: 'species' 

请您参考如下方法:

我认为您已将数据从 numpy 正确加载到 pandas 数据帧,如果您只是停止使用 hue,它应该可以工作:

sns.pairplot(df, size=2.5) 

虽然我在 hue 方面遇到了问题。我认为这会起作用,而且它有点起作用,但是有很多错误/警告代码,并且现有的图是 3x3 而不是 2x2。在 iris 示例中,seaborn 知道不绘制物种,但在这里却不知道?

df['species'] = np.random.choice(2,150)  
sns.pairplot(df, hue="species", size=2.5) 

KeyError                                  Traceback (most recent call last) 
<ipython-input-148-cae05573d2d1> in <module>() 
      6  
      7 df['species'] = np.random.choice(2,150) 
----> 8 sns.pairplot(df, hue="species", size=2.5) 
      9  
     10 sns.plt.show() 
 
/Users/John/anaconda/lib/python2.7/site-packages/seaborn/linearmodels.pyc in pairplot(data, hue, hue_order, palette, vars, x_vars, y_vars, kind, diag_kind, markers, size, aspect, dropna, plot_kws, diag_kws, grid_kws) 
   1756     # Add a legend 
   1757     if hue is not None: 
-> 1758         grid.add_legend() 
   1759  
   1760     return grid 
 
/Users/John/anaconda/lib/python2.7/site-packages/seaborn/axisgrid.pyc in add_legend(self, legend_data, title, label_order) 
     47             # Draw a full-figure legend outside the grid 
     48             figlegend = plt.figlegend(handles, label_order, "center right", 
---> 49                                       scatterpoints=1) 
     50             self._legend = figlegend 
     51             figlegend.set_title(title) 
 
/Users/John/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.pyc in figlegend(handles, labels, loc, **kwargs) 
    662  
    663     """ 
--> 664     l = gcf().legend(handles, labels, loc, **kwargs) 
    665     draw_if_interactive() 
    666     return l 
 
/Users/John/anaconda/lib/python2.7/site-packages/matplotlib/figure.pyc in legend(self, handles, labels, *args, **kwargs) 
   1193         .. plot:: mpl_examples/pylab_examples/figlegend_demo.py 
   1194         """ 
-> 1195         l = Legend(self, handles, labels, *args, **kwargs) 
   1196         self.legends.append(l) 
   1197         l._remove_method = lambda h: self.legends.remove(h) 
 
/Users/John/anaconda/lib/python2.7/site-packages/matplotlib/legend.pyc in __init__(self, parent, handles, labels, loc, numpoints, markerscale, scatterpoints, scatteryoffsets, prop, fontsize, borderpad, labelspacing, handlelength, handleheight, handletextpad, borderaxespad, columnspacing, ncol, mode, fancybox, shadow, title, framealpha, bbox_to_anchor, bbox_transform, frameon, handler_map) 
    369  
    370         if framealpha is None: 
--> 371             self.get_frame().set_alpha(rcParams["legend.framealpha"]) 
    372         else: 
    373             self.get_frame().set_alpha(framealpha) 
 
/Users/John/anaconda/lib/python2.7/site-packages/matplotlib/__init__.pyc in __getitem__(self, key) 
    844             except (ValueError, RuntimeError): 
    845                 # force the issue 
--> 846                 warnings.warn(_rcparam_warn_str.format(key=repr(k), 
    847                                                        value=repr(v), 
    848                                                        func='__init__')) 
 
KeyError: u'legend.framealpha'