2016-05-05 31 views
1

我正在使用熊貓0.18。我有這樣一個數據幀:添加傳說以散點圖區分顏色?

code proportion percent_highcost total_quantity 
A81  0.7   76     1002 
A81  0.0   73     1400 

而且我畫的散點圖這樣的:

colours = np.where(df['proportion'] > 0, 'r', 'b') 
df.plot.scatter(y='percent_highcost', x='total_quantity', c=colours) 

這個效果很好,但我不知道如何添加一個傳說,表示什麼兩種顏色的意思。

我試過plt.legend(['Non-dispensing', 'dispensing'], loc=1)但是這會產生一個奇怪的結果 - 我猜是因爲只有一個系列:

enter image description here

誰能指教?

+0

我建議使用'fig.colorbar(SC)''那裏是sc'藝術家「分散」。您可能不得不使用'ax.scatter'而不是'df.plot'來輕鬆訪問該藝術家。 – tacaswell

回答

0

劇情獨特DataFrame s的同樣軸線

繪製多個系列(未pandasSeries)在分散可以通過一個條件分離DataFrame秒,然後繪製它們作爲具有獨特的顏色分開的散射完成在同一個軸上。這在answer中顯示。我將在這裏重現你的數據。

注:這在IPython中/ Jupyter筆記本做

%matplotlib inline 

import pandas as pd 
from cStringIO import StringIO 

# example data 
text = ''' 
code proportion percent_highcost total_quantity 
A81  0.7   76     1002 
A81  0.0   73     1400 
A81  0.1   77     1300 
A81  0.0   74     1200 
A81  -0.1   78     1350 
''' 

# read in example data 
df = pd.read_csv(StringIO(text), sep='\s+') 

print 'Original DataFrame:' 
print df 
print 

# split the DataFrame into two DataFrames 
condition = df['proportion'] > 0 
df1 = df[condition].dropna() 
df2 = df[~condition].dropna() 

print 'DataFrame 1:' 
print df1 
print 

print 'DataFrame 2:' 
print df2 
print 

# Plot 2 DataFrames on one axis 
ax = df1.plot(kind='scatter', x='total_quantity', y='percent_highcost', c='b', s=100, label='Non-Dispensing') 
df2.plot(kind='scatter', x='total_quantity', y='percent_highcost', c='r', s=100, label='Dispensing', ax=ax) 

Original DataFrame: 
    code proportion percent_highcost total_quantity 
0 A81   0.7    76   1002 
1 A81   0.0    73   1400 
2 A81   0.1    77   1300 
3 A81   0.0    74   1200 
4 A81  -0.1    78   1350 

DataFrame 1: 
    code proportion percent_highcost total_quantity 
0 A81   0.7    76   1002 
2 A81   0.1    77   1300 

DataFrame 2: 
    code proportion percent_highcost total_quantity 
1 A81   0.0    73   1400 
3 A81   0.0    74   1200 
4 A81  -0.1    78   1350 

Two Series Scatter Plot