简体   繁体   中英

How to accurately plot the legend of multi-layer plot (boxplot and lineplot)?

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

样地

I overlay a lineplot to a boxplot as in the image above, and draw the legend manually using matplotlib.

But seaborn sets the saturation of the colors, whose default value is 0.75 (I set it to 0.5 make the difference clear). So the legend color generated by matplotlib is not accurate. Is there any way to change the saturation of the matplotlib legend? Or how can I draw legend color accurately, except setting saturation=1 .

Use seaborn's desaturate function

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM