Python seaborn组合图如何像FaceGrid一样被分离?

2024-04-25 00:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个带有两个y轴的组合折线图,用于聚合两个“模型”(蓝色小部件和绿色小部件)的数据。我想做的是根据“data1”数据框中“model”列的值创建两个单独的组合图(图1是蓝色小部件的组合图,图2是绿色小部件的组合图,顺序无关紧要)。如何做到这一点

数据帧:

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

data1 = {'revenue': [345,543,434,678,456,544,356,765,566,434],
        'month': ['01-01-2020', '01-01-2020','01-01-2020','01-02-2020','01-02-2020','01-02-2020','01-02-2020','01-03-2020','01-03-2020','01-03-2020'],
        'model': ['Blue Widget', 'Green Widget','Green Widget','Blue Widget','Blue Widget','Green Widget','Blue Widget','Blue Widget','Green Widget','Green Widget']}
data2 = {'AOV': [45,65,56,67,69,54,56,66,44,55],
        'month': ['01-01-2020', '01-01-2020','01-01-2020','01-02-2020','01-02-2020','01-02-2020','01-02-2020','01-03-2020','01-03-2020','01-03-2020']}

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

以下是需要分开的图表,类似于Facetgrid,基于Data2中的“model”列:

#Create combo chart
fig, ax1 = plt.subplots(figsize=(10,6))
color = 'tab:green'
#line plot1 creation
ax1.set_title('Revenue vs Average Order Value', fontsize=16)
ax1.set_xlabel('Day', fontsize=16)
ax1 = sns.lineplot(x='month', y='revenue', data = df1, ci=None)
ax1.tick_params(axis='y')
ax1.set_ylabel('Revenue', fontsize=16)
#specify we want to share the same x-axis
ax2 = ax1.twinx()
color = 'tab:red'
#line plot2 creation
ax2.set_ylabel('AOV', fontsize=16)
ax2 = sns.lineplot(x='month', y='AOV', data = df2, sort=False, color=color, ci=None)
ax2.tick_params(axis='y', color=color)
#show plot
plt.show()

Tags: 数据importmodel部件asgreenbluewidget
1条回答
网友
1楼 · 发布于 2024-04-25 00:33:43

首先,合并您的两个数据帧(我假设它们按行匹配,否则请根据需要找出如何合并它们)

然后,您可以创建一个自定义打印函数以传递给FacetGrid

def combo(*cols,**kwargs):
    df = kwargs.pop('data')
    color = kwargs.pop('color')
    colors = kwargs.pop('colors')
    ax1 = plt.gca()
    ax1 = sns.lineplot(x=cols[0], y=cols[1], data = df, ci=None, ax=ax1, color=colors[0], **kwargs)
    #specify we want to share the same x-axis
    ax2 = ax1.twinx()
    ax2 = sns.lineplot(x=cols[0], y=cols[2], data = df, sort=False, ci=None, ax=ax2, color=colors[1], **kwargs)

g = sns.FacetGrid(data=df3, col='model')
g.map_dataframe(combo, 'month', 'revenue', 'AOV', colors=['tab:green', 'tab:red'])

enter image description here

相关问题 更多 >