如何在保留图例颜色与填充图案的前提下修改图例标题和标签?
问题:修改Seaborn柱状图图例时保留颜色与填充图案
我通过以下代码创建了带有填充图案的柱状图:
import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") hatches = ['\\\\', '//'] fig, ax = plt.subplots(figsize=(6,3)) sns.barplot(data=tips, x="day", y="total_bill", hue="time") # 设置填充图案 for hues, hatch in zip(ax.containers, hatches): for hue in hues: hue.set_hatch(hatch) plt.legend() plt.show()
该代码生成的图表包含带填充图案的柱状图,图例也能正确显示颜色和填充样式。
但当我尝试修改图例标题和标签时,图例的颜色和填充图案丢失了:
import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") hatches = ['\\\\', '//'] fig, ax = plt.subplots(figsize=(6,3)) sns.barplot(data=tips, x="day", y="total_bill", hue="time") # 设置填充图案 for hues, hatch in zip(ax.containers, hatches): for hue in hues: hue.set_hatch(hatch) # 修改图例标题和标签后样式丢失 plt.legend(title='My Title', labels=['Lunch_1','Dinner_2'], loc=1) plt.show()
解决方案
方法1:基于原图例的handles修改标签和标题
直接调用plt.legend()传入新标签时,Matplotlib会重新生成图例,不会沿用已设置的填充样式。我们可以先获取包含样式信息的原图例handles,再传入legend:
import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") hatches = ['\\\\', '//'] fig, ax = plt.subplots(figsize=(6,3)) sns.barplot(data=tips, x="day", y="total_bill", hue="time") # 设置填充图案 for hues, hatch in zip(ax.containers, hatches): for hue in hues: hue.set_hatch(hatch) # 获取原图例的handles和labels handles, _ = ax.get_legend_handles_labels() # 传入handles保留样式,同时设置新标签和标题 plt.legend(handles=handles, labels=['Lunch_1','Dinner_2'], title='My Title', loc=1) plt.show()
方法2:直接修改已生成的图例对象
先获取已经创建好的图例对象,直接修改它的标题和文本标签,完全保留原有样式:
import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") hatches = ['\\\\', '//'] fig, ax = plt.subplots(figsize=(6,3)) sns.barplot(data=tips, x="day", y="total_bill", hue="time") # 设置填充图案 for hues, hatch in zip(ax.containers, hatches): for hue in hues: hue.set_hatch(hatch) # 先生成默认图例 plt.legend() # 获取图例对象 leg = ax.get_legend() # 修改图例标题 leg.set_title('My Title') # 逐个修改标签文本 for text, new_label in zip(leg.texts, ['Lunch_1','Dinner_2']): text.set_text(new_label) plt.show()
内容的提问来源于stack exchange,提问作者Ernesto
相关产品推荐
相关产品推荐

