2016-08-11 85 views
3

我确信我在这里搞了一件非常简单的事情,但似乎无法弄清楚。我只是试图通过循环访问一个数据帧并重复调用ax.scatter来将每组数据绘制为每组不同颜色的散点图。一个最小的例子是:matplotlib中的多个散点图中的意外颜色

import numpy as np; import pandas as pd; import matplotlib.pyplot as plt; import seaborn as sns 
%matplotlib inline 

df = pd.DataFrame({"Cat":list("AAABBBCCC"), "x":np.random.rand(9), "y":np.random.rand(9)}) 

fig, ax = plt.subplots() 
for i,cat in enumerate(df.Cat.unique()): 
    print i, cat, sns.color_palette("husl",3)[i] 
    ax.scatter(df[df.Cat==cat].x.values, df[df.Cat==cat].y.values, marker="h",s=70, 
       label = cat, color=sns.color_palette("husl",3)[i]) 
ax.legend(loc=2) 

我加入了print声明为自己的理智,以确认我确实通过组循环,并选择不同的颜色。然而,输出如下:

enter image description here

(如果这是稍微很难看到:组A,B和C根据传说有三个非常相似的蓝调,但所有scatterpoints有不同,看上去无关的颜色,甚至在群组中都不相同)

这是怎么回事?

回答

1

本来应该花更多的时间削下来的最低工作的例子。原来问题出在sns.color_palette的调用中,它返回一个(float,float,float)元组,它混淆了scatter,因为它显然将其中一个数字解释为alpha值。

问题是由替换

color = sns.color_palette("husl",3)[i] 

解决了

color = sns.color_palette("husl",3)[i] + (1.,) 

到用于α-添加显式值。

+0

哇!很好自己搞清楚。 –

1

你可以通过指定目标ax和重复的曲线绘制的多个列组在一个单一的轴,ax使用的pandasscatter()方法。

# set random seed 
np.random.seed(42)      

fig, ax = plt.subplots() 
for i,label in enumerate(df['Cat'].unique()): 
    # select subset of columns equal to a given label 
    df['X'] = df[df['Cat']==label]['x']  
    df['Y'] = df[df['Cat']==label]['y'] 
    df.plot.scatter(x='X',y='Y',color=sns.color_palette("husl",3)[i],label=label,ax=ax) 
ax.legend(loc=2) 

enter image description here

+0

确实存在一种可能性,遗憾的是不是我的用例,因为我在地图上绘图,所以必须使用'Basemap'对象的'scatter'方法。 –

相关问题