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

时间:2018-02-08 20:54:15

标签: python matplotlib plot legend seaborn

我有一个seaborn散点图(lmplot)超过10K点。为了感知所有数据,当绘图尺寸较大(使标记相对较小)并且标记上的alpha较低时,它会更好地工作。但是,这使得图例上的标记难以区分。 如何在Seaborn中设置标记大小和标记alpha?

我发现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 个答案:

答案 0 :(得分: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