如何让seaborn kdeplot的图例显示轮廓线颜色?
解决seaborn 2D kdeplot图例不显示轮廓线颜色的问题
在seaborn v0.12.0中,2D kdeplot() 默认会绘制填充的密度区域(fill=True),此时图例默认仅展示填充色块,不会关联轮廓线的颜色。以下是两种可行的解决方法:
方法1:关闭填充,仅绘制轮廓线
通过添加fill=False参数,让kdeplot()只绘制密度轮廓线,图例将自动对应显示线条颜色,操作简单直接。
import numpy as np import seaborn as sns import matplotlib.pyplot as plt fig, ax = plt.subplots() sns.kdeplot(x=np.random.random(30), y=np.random.random(30), label="dist1", ax=ax, fill=False) sns.kdeplot(x=np.random.random(30)+1, y=np.random.random(30)+1, label="dist2", ax=ax, fill=False) ax.legend() plt.show()
方法2:保留填充,同时显示轮廓线图例
如果需要保留填充效果,可通过调整图例的元素样式,让填充色块显示对应的轮廓线:
方式A:自定义图例元素
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib.patches import Patch fig, ax = plt.subplots() # 指定linewidth确保轮廓线可见 sns.kdeplot(x=np.random.random(30), y=np.random.random(30), label="dist1", ax=ax, linewidth=2) sns.kdeplot(x=np.random.random(30)+1, y=np.random.random(30)+1, label="dist2", ax=ax, linewidth=2) # 获取原有图例的标签和样式,创建带轮廓的填充色块作为图例元素 handles, labels = ax.get_legend_handles_labels() custom_handles = [Patch(facecolor=h.get_facecolor(), edgecolor=h.get_edgecolor(), linewidth=2) for h in handles] ax.legend(handles=custom_handles, labels=labels) plt.show()
方式B:修改现有图例样式
直接修改原有图例中填充色块的属性,添加轮廓线:
import numpy as np import seaborn as sns import matplotlib.pyplot as plt fig, ax = plt.subplots() sns.kdeplot(x=np.random.random(30), y=np.random.random(30), label="dist1", ax=ax, linewidth=2) sns.kdeplot(x=np.random.random(30)+1, y=np.random.random(30)+1, label="dist2", ax=ax, linewidth=2) # 获取图例元素,设置轮廓线颜色和宽度 handles, labels = ax.get_legend_handles_labels() for handle in handles: handle.set_edgecolor(handle.get_edgecolor()) handle.set_linewidth(2) ax.legend(handles=handles, labels=labels) plt.show()
内容的提问来源于stack exchange,提问作者Vecko
相关产品推荐
相关产品推荐

