Skip to main content
 首页 » 编程设计

python之控制散点图中的颜色

2025年02月15日12Renyi-Fan

这是一个模拟的 DataFrame:

import pandas as pd 
groups=pd.DataFrame({'Morph':np.random.choice(['S', 'Red'], 50), 
                 'Tcross':np.random.rand(50)*0.2 ,   
                 'DeltaR12':np.random.rand(50)*2.0}) 

我这样绘制散点图:

import matplotlib.pyplot as plt 
 
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet) 
colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random') 
 
fig, ax = plt.subplots() 
ax.set_color_cycle(colors) 
ax.margins(0.05) 
for name, group in groups: 
    ax.plot(group.DeltaR12, group.Tcross, marker='o', 
            linestyle='', ms=5, label=name) 
legend = ax.legend(numpoints=1, loc='upper left', shadow=True) 
 
# Hereafter, code for the subsidiary question at the end or the post 
# code doesn't produce anything 
frame = legend.get_frame() 
frame.set_facecolor('0.90') 
 
for label in legend.get_lines(): 
    label.set_linewidth(1.5)   
 
 
 
ax.set_xlabel('$\Delta R_{12}$') 
ax.set_ylabel('$T_{cross}$') 

导致

或者,或者,使用 seaborn 的魔法,在一行中:

sns.swarmplot(x="DeltaR12", y="Tcross", data=groups, hue="MorphCen", size=6) 

(哪些与我的实际 DataFrame 分组,甚至不必删除其他列)

导致

我想控制类别的颜色:将标签“红色”绘制成黄色或蓝色看起来很愚蠢!此外,螺旋星系是蓝色的,所以用紫色绘制“S”类别看起来很愚蠢。如何轻松控制这种颜色选择?

辅助,如果有人知道如何在图例周围画一个框,那就太好了,我不了解自动标签的文档,只了解手动设置的标签。 :) 我已经在第一个代码中尝试了一些东西,如评论中所述,但它没有产生任何结果。

谢谢

请您参考如下方法:

所以我想出了如何做到这一点。第一种方式,感谢 sgDysregulation(我没有以非常好的方式实现它,我确信有比这更好的方法 ind )。

colour_lst=['r','b'] 
 
fig, ax = plt.subplots() 
ax.set_color_cycle(colors) 
ax.margins(0.05) 
ind=0 
for name, group in groups: 
    ax.plot(group.DeltaR12, group.Tcross, marker='o', 
            color = colour_lst[ind] ,linestyle='', ms=5, label=name) 
    ind+=1   
 
ax.set_xlabel('$\Delta R_{12}$') 
ax.set_ylabel('$T_{cross}$') 

第二,更优雅:

def transcocol(morph): 
    if (morph == 'S'): 
        return'b' 
    else: 
        return'r' 
MLtargetColour = MLtarget.apply (lambda x: transcocol (x)) 
pl.scatter(group.DeltaR12, group.Tcross, c=MLtargetColour); 

最后一个:

sns.swarmplot(x="DeltaR12", y="Tcross",  
              data=group, hue="MorphGal", palette="Set1", 
              hue_order=['Red','S'], size=6) 

非常感谢。