首页 > 解决方案 > 如何准确绘制多层图(箱线图和线图)的图例?

问题描述

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.

标签: pythonmatplotlibseaborn

解决方案


使用seaborn的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')

在此处输入图像描述


推荐阅读