繁体   English   中英

在 Seaborn 上使用 Facetgrid 添加辅助 y 轴

[英]Adding secondary y-axis with Facetgrid on Seaborn

我有一个队列数据集(从 1 天到 365 天),现在我在 Seaborn 中这样表示。蓝线是以前的结果,橙色是当前结果,条形是它们之间的增量百分比:

在此处输入图像描述

但是,我需要在与带有次轴的线图相同的 plot 上添加条形图。

对于 Facetgrid 的每个 plot,我预期的 output 是这样的:

在此处输入图像描述

我在宽格式上使用的 dataframe 样本,我将其分成两部分,以将日期与 de delta 和 pre y post 结果分开。 由于队列数据,我需要这种方式:

在此处输入图像描述

这是我用于 plot 第一个图表的代码:

fig, ax1 = plt.subplots() # initializes figure and plots

ax2 = ax1.twinx() # applies twinx to ax2, which is the second y axis. 

g = sns.FacetGrid(df_ads_long_st, col="m", hue="status", height=5, aspect=0.8)
g.map(sns.lineplot, "dx", "value_a", alpha=.7, ax = ax1)

g = sns.FacetGrid(df_ads_long_de, col="m", hue="status", height=5, aspect=0.8)
g.map(sns.barplot, "dx", "value_a", alpha=.7, ax = ax2)

# these lines add the annotations for the plot. 
ax1.set_xlabel('DX')
ax1.set_ylabel('ARPU', color='b')
ax2.set_ylabel('Delta', color='r')

plt.show(); # shows the plot. 

还有其他日子吗?

谢谢!

我有一个类似的要求。 诀窍是创建您自己的 function。在这个 function 中,您创建一个双轴。

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns


def facetgrid_two_axes(data: pd.DataFrame, x_name: str, y1_name: str, y2_name: str, ylabel1: str, ylabel2: str):
    ax1 = plt.gca()
    sns.lineplot(data[x_name], data[y1_name], alpha=.7, ax=ax1)
    ax1.set_ylabel(ylabel1)

    ax2 = ax1.twinx()
    sns.barplot(data[x_name], data[y2_name], alpha=.7, ax=ax2)
    ax2.set_ylabel(ylabel2)


if __name__ == '__main__':
    df_ads_long_st = pd.DataFrame(...) // Your data

    g = sns.FacetGrid(df_ads_long_st, col="m", hue="status", height=5, aspect=0.8)
    g.map_dataframe(facetgrid_two_axes, x_name="dx", y1_name="value_a", y2_name="value_a", alpha=.7,
                    ylabel1='Counts', ylabel2='Detection rates')

    g.set_xlabels('x data')

    plt.show()

我的一个缺点是,ylabels 显示在每个 plot 上,而不是仅显示在图形的边界上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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