2015-07-19 59 views
0

考慮下面的數據框(以大熊貓):如何用matplotlib繪製不同顏色和形狀的多個組?

 X Y Type Region 
index 
1  100 50 A  US 
2  50 25 A  UK 
3  70 35 B  US 
4  60 40 B  UK 
5  80 120 C  US 
6  120 35 C  UK 

爲了生成數據框:

import pandas as pd 

data = pd.DataFrame({'X': [100, 50, 70, 60, 80, 120], 
        'Y': [50, 25, 35, 40, 120, 35], 
        'Type': ['A', 'A', 'B', 'B', 'C', 'C'], 
        'Region': ['US', 'UK'] * 3 
        }, 
        columns=['X', 'Y', 'Type', 'Region'] 
     ) 

我設法使XY散點圖,由Type着色和成型Region。我怎麼能在matplotlib中實現它?

回答

2

隨着越來越多的熊貓:

from pandas import DataFrame 
from matplotlib.pyplot import show, subplots 
from itertools import cycle # Useful when you might have lots of Regions 

data = DataFrame({'X': [100, 50, 70, 60, 80, 120], 
        'Y': [50, 25, 35, 40, 120, 35], 
        'Type': ['A', 'A', 'B', 'B', 'C', 'C'], 
        'Region': ['US', 'UK'] * 3 
        }, 
        columns=['X', 'Y', 'Type', 'Region'] 
     ) 

cs = {'A':'red', 
     'B':'blue', 
     'C':'green'} 

markers = ('+','o','>') 
fig, ax = subplots() 

for region, marker in zip(set(data.Region),cycle(markers)): 
    reg_data = data[data.Region==region] 
    reg_data.plot(x='X', y='Y', 
      kind='scatter', 
      ax=ax, 
      c=[cs[x] for x in reg_data.Type], 
      marker=marker, 
      label=region) 
ax.legend() 
show() 

enter image description here

對於這種多維的情節,不過,退房seaborn(與大熊貓效果很好)。

0

一種方法是執行以下操作。這是不優雅,但工程 進口matplotlib.pyplot如PLT 進口matplotlib爲MPL 進口numpy的爲NP plt.ion()

colors = ['g', 'r', 'c', 'm', 'y', 'k', 'b'] 
markers = ['*','+','D','H'] 
for iType in range(len(data.Type.unique())): 
    for iRegion in range(len(data.Region.unique())): 
     plt.plot(data.X.values[np.bitwise_and(data.Type.values == data.Type.unique()[iType], 
               data.Region.values == data.Region.unique()[iRegion])], 
       data.Y.values[np.bitwise_and(data.Type.values == data.Type.unique()[iType], 
               data.Region.values == data.Region.unique()[iRegion])], 
       color=colors[iType],marker=markers[iRegion],ms=10) 

我不熟悉的熊貓,但必須有一些更優雅過濾的方法。可以使用從matplotlib和傳統的彩色週期markers.MarkerStyle.markers.keys()獲得的標記列表可以使用GCA()獲得._ get_lines.color_cycle.next()

+0

謝謝。我在iPython筆記本上嘗試了您的解決方案,但只繪製了兩點。 – Zelong

+0

@Zelong歡迎您。當我在這裏運行代碼時,我得到了全部6分。三種不同的顏色和兩種不同的形狀(+和*)。看起來很稀少,只有6分 –

相關問題