2017-05-14 91 views
2

pyplot.scatter允許傳遞到c=與數組對應的數組,然後根據這些組着色點。但是,這似乎不支持在沒有分別繪製每個組的情況下生成圖例。散點圖與圖例顏色的傳說沒有多次調用plt.scatter

因此,舉例來說,一個散點圖用彩色可通過遍歷組和繪製每個分別生成基團:

import matplotlib.pyplot as plt 
from sklearn.datasets import load_iris 
feats = load_iris()['data'] 
target = load_iris()['target'] 

f, ax = plt.subplots(1) 
for i in np.unique(target): 
    mask = target == i 
    plt.scatter(feats[mask, 0], feats[mask, 1], label=i) 
ax.legend() 

其產生:

enter image description here

我可以實現一個類似的外觀,但沒有迭代每個組:

f, ax = plt.subplots(1) 
ax.scatter(feats[:, 0], feats[:, 1], c=np.array(['C0', 'C1', 'C2'])[target]) 

但我找不出一種方法來生成相應的圖例與這第二個策略。我所遇到的所有示例都反覆遍歷了這些組,這似乎不太理想。我知道我可以手動生成一個圖例,但似乎過於繁瑣。

回答

0

,解決這個問題還採用了循環,所以這可能是預期的用途matplotlib散射例如:https://matplotlib.org/examples/lines_bars_and_markers/scatter_with_legend.html

如果你的更大的目標是隻作策劃和標籤分類數據更簡單,你應該考慮Seaborn 。這是一個類似的問題Scatter plots in Pandas/Pyplot: How to plot by category

一種實現您的目標的方法是使用帶標籤列的熊貓。一旦你在熊貓數據框中有數據,你可以使用Seaborn pairplot來製作這種情節。 (Seaborn也有可作爲標記的數據幀虹膜數據集)

import seaborn as sns 
iris = sns.load_dataset("iris") 
sns.pairplot(iris, hue="species") 

enter image description here

如果你只是想前兩個功能,可以使用

sns.pairplot(x_vars=['sepal_length'], y_vars=['sepal_width'], data=iris, hue="species", size=5) 

enter image description here

如果你真的想使用sklearn數據字典,你可以將它拉入數據框如下:

import pandas as pd 
from sklearn.datasets import load_iris 
import numpy as np 

feats = load_iris()['data'].astype('O') 
target = load_iris()['target'] 
feat_names = load_iris()['feature_names'] 
target_names = load_iris()['target_names'].astype('O') 

sk_df = pd.DataFrame(
    np.hstack([feats,target_names[target][:,np.newaxis]]), 
    columns=feat_names+['target',]) 
sns.pairplot(sk_df, vars=feat_names, hue="target") 
+0

我知道你可以在seaborn中做到這一點,但我的實際使用案例(我在繪製3D散點圖)seaborn不支持。在引擎蓋下,seaborn正在使用matplotlib來實際進行繪圖 - 我想我可以通過並瞭解seaborn如何在pairplot(或regplot)中生成散點圖和相關的圖例。我的猜測是它像在我的第一批示例代碼中那樣循環着各組。 – user3014097