如何准确绘制多层图例(箱线图和线图)的图例?

时间:2020-04-01 04:36:21

标签: python matplotlib seaborn

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')

sample plot

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

但是seaborn设置颜色的饱和度,其默认值为0.75(我将其设置为0.5可以使差异明显)。因此,matplotlib生成的图例颜色不正确。有什么方法可以改变matplotlib图例的饱和度吗?或者如何设置设置saturation=1除外的准确绘制图例颜色。

1 个答案:

答案 0 :(得分:0)

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

enter image description here