【问题标题】:How to accurately plot the legend of multi-layer plot (boxplot and lineplot)?如何准确绘制多层图(箱线图和线图)的图例?
【发布时间】:2020-04-01 04:36:21
【问题描述】:
import numpy as np
import seaborn as sns
from matplotlib.patches import Patch
from matplotlib.lines import Line2D

data_box = np.random.random((10, 3))
data_line = np.random.random(3)

ax = sns.boxplot(data=data_box, color='red', saturation=0.5)
sns.lineplot(data=data_line, color='blue')
legend_elements = [Line2D([0], [0], color='blue', lw=4, label='box'),
                   Patch(facecolor='red', edgecolor='grey', linewidth=1.5,
                         label='line')]
ax.legend(handles=legend_elements, fontsize='xx-large')

如上图所示,我将线图叠加到箱线图上,然后使用 matplotlib 手动绘制图例。

但是 seaborn 设置了颜色的饱和度,其默认值为 0.75(我将其设置为 0.5 以使差异清晰)。所以matplotlib生成的图例颜色是不准确的。有什么办法可以改变matplotlib图例的饱和度?或者我怎样才能准确地绘制图例颜色,除了设置saturation=1

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    使用seaborn's desaturate函数

    import numpy as np
    import seaborn as sns
    from matplotlib.patches import Patch
    from matplotlib.lines import Line2D
    
    data_box = np.random.random((10, 3))
    data_line = np.random.random(3)
    
    fig, ax = plt.subplots()
    ax = sns.boxplot(data=data_box, color='red', saturation=0.5)
    sns.lineplot(data=data_line, color='blue')
    legend_elements = [Line2D([0], [0], color='blue', lw=4, label='box'),
                       Patch(facecolor=sns.desaturate('red',0.5), edgecolor='grey', linewidth=1.5,
                             label='line')]
    ax.legend(handles=legend_elements, fontsize='xx-large')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多