首页 文章

如何设置图例标记大小和alpha?

提问于
浏览
3

我有一个超过10K点的seaborn散点图( lmplot ) . 为了感知所有数据,当绘图尺寸较大(使标记相对较小)并且标记上的alpha较低时,它会更好地工作 . 但是,这使得图例上的标记难以区分 . How does one set the marker size and marker alpha in Seaborn?

我看到 g._legend 有一个 markersize 属性,但直接设置它没有做任何事情 .

示例

import numpy as np
import pandas as pd
import seaborn as sns

n_group = 4000

pos = np.concatenate((np.random.randn(n_group,2) + np.array([-1,-1]),
                      np.random.randn(n_group,2) + np.array([0.2, 1.5]),
                      np.random.randn(n_group,2) + np.array([0.6, -1.8])))
df = pd.DataFrame({"x": pos[:,0], "y": pos[:, 1], 
                   "label": np.repeat(range(3), n_group)})

g = sns.lmplot("x", "y", df, hue = "label", fit_reg = False, 
               size = 8, scatter_kws = {"alpha": 0.1})
g._legend.set_title("Clusters")

Scatter plot of three dense clusters of points, with different colors for each cluster. The cluster colors are easily distinguished in the plot, but the markers in the legend are barely visible.

1 回答

  • 5

    您可以通过设置图例标记本身的Alpha值来完成此操作 . 您也可以使用 _sizes 在相同的for循环中设置标记大小:

    n_group = 4000
    
    pos = np.concatenate((np.random.randn(n_group,2) + np.array([-1,-1]),
                          np.random.randn(n_group,2) + np.array([0.2, 1.5]),
                          np.random.randn(n_group,2) + np.array([0.6, -1.8])))
    df = pd.DataFrame({"x": pos[:,0], "y": pos[:, 1], 
                       "label": np.repeat(range(3), n_group)})
    
    g = sns.lmplot("x", "y", df, hue = "label", fit_reg = False, 
                   size = 8, scatter_kws = {"alpha": 0.1})
    g._legend.set_title("Clusters")
    
    for lh in g._legend.legendHandles: 
        lh.set_alpha(1)
        lh._sizes = [50] 
        # You can also use lh.set_sizes([50])
    

    enter image description here

相关问题