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

我想用Scatterplot Matrixlabels构建自己的colors。我喜欢这个例子: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'

python大神给出的解决方案

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

sns.pairplot(df, size=2.5)

我在使用hue时遇到了问题。我以为这会行得通,并且确实可以,但是有很多错误/警告代码,并且现有的绘图是3x3而不是2x2。在虹膜示例中,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'