python - 如何准确绘制多层图(箱线图和线图)的图例?
问题描述
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
.
解决方案
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')
推荐阅读
- php - SQLlite 左连接引用仅带回其中一张表的结果
- python - 如何通过测试修改类数据?
- apache-nifi - 使用 TLS 和 LDAP 身份验证启动 NiFi 1.14.1 时出现问题
- javascript - 如何在文本区域中显示 HTML 电子邮件字符串?
- php - Browsersync 使 Chrome 崩溃
- c - 如何在C中使用两次变量?
- react-native - 如何使用 fetch 从 react native(expo)上传图像到节点 js 服务器
- javascript - 使用自动完成作为自定义过滤器的 MUI 数据表
- file-upload - Postman 在 runner 中迭代上传文件
- r - 带有日期输入或下拉列表的闪亮可编辑 DT 表