将 sns.FacetGrid() 与自定义函数结合使用时规范图例外观 [英] Normalizing legend appearance when combining sns.FacetGrid() with custom functions

查看:42
本文介绍了将 sns.FacetGrid() 与自定义函数结合使用时规范图例外观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义函数 twin_lineplot() 构建 sns.FacetGrid 图;但无法弄清楚如何加入"图例标签 label1label2.

I'm trying to build a sns.FacetGrid plot using a custom function twin_lineplot(); but unable to figure out how to "join" the legend labels label1 and label2.

下面只是一个简单的例子来演示我的问题.我希望实现一个可扩展的解决方案(两个图例中的多个标签要组合).

The below is just a simplified example to demonstrate my problem. I hope to achieve a solution that is scalable (multiple labels in both legends to be combined).

给定数据集:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

date_today= datetime.now()
tips = sns.load_dataset("tips")
days = pd.date_range(date_today, date_today + timedelta(tips.shape[0]-1), freq='D')
tips['date'] = days

我想用图例绘制 sns.FacetGrid() 图.但是,我在下面的尝试将图例拆分为标记为 label2 的内部图和外部图 label1

I would like to plot a sns.FacetGrid() plot with a legend. However, my attempt below splits the legend to inner plot marked as label2 and outer plot label1

def twin_lineplot(x,y,color,**kwargs):
    ax = plt.twinx()
    sns.lineplot(x=x,y=y,color=color,**kwargs, ax=ax)

g = sns.FacetGrid(tips, row='smoker', col='time')
g.map(sns.lineplot, 'date', 'tip', color='b', label='label1')
g.map(twin_lineplot, 'date', 'total_bill', color='g', label='label2')
g.add_legend()
g.fig.autofmt_xdate()
plt.show()

如何组合要显示在外部图例中的两个图例标签(当前显示 label1 的位置)?

How do I combine the two legend labels to be displayed in the outer legend (where label1 is currently shown)?

我想扩展解决方案以解决以下问题:

I would like to scale the solution to solve the below:

推荐答案

基本上可以使用 matplotlib 子属性.

You can basically use matplotlib child property.

以下代码可能对您有所帮助.

Below code might help you.

g = sns.FacetGrid(tips,row='sex',hue='smoking_status',height=3,aspect=3, legend_out=True)
g = g.map(plt.scatter,'total_bill','tip').add_legend()
plt.show()

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')

# more informative values
condition = tips['smoker'] == 'Yes'
tips['smoking_status'] = ''
tips.loc[condition,'smoking_status'] = 'Smoker'
tips.loc[~condition,'smoking_status'] = 'Non-Smoker'

g = sns.FacetGrid(tips,row='sex',hue='smoking_status',height=3,aspect=3)
g = g.map(plt.scatter,'total_bill','tip')
for ax in g.axes.flat:
    box = ax.get_position()
    ax.set_position([box.x0,box.y0,box.width*0.85,box.height])

plt.legend(loc='upper left',bbox_to_anchor=(1,0.5))
plt.show()

这篇关于将 sns.FacetGrid() 与自定义函数结合使用时规范图例外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆