2015-07-19 132 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分 –

相关问题