【问题标题】:subplots in python with multiple line charts using pandas ans seabornpython中的子图,带有使用熊猫和seaborn的多个折线图
【发布时间】:2020-06-22 09:33:23
【问题描述】:

我有一个如下图所示的数据框

product    bought_date     Monthly_profit     Average_discout
A          2016            85000000           5
A          2017            55000000           5.6
A          2018            45000000           10
A          2019            35000000           9.8
B          2016            75000000           5
B          2017            55000000           4.6
B          2018            75000000           11
B          2019            45000000           9.8
C          2016            95000000           5.3
C          2017            55000000           5.1
C          2018            50000000           10.2
C          2019            45000000           9.8

从上面我想绘制 3 个子图。

一个用于产品 A、B 和 C。

在每个子图中应该有 3 条线图,其中

X axis = bought_date
Y axis1 = Monthly_profit
Y axis2 = Average_discout

我试过下面的代码。

sns.set(style = 'darkgrid')
sns.lineplot(x = 'bought_date', y  = 'Monthly_profit', style = 'product', 
             data = df1, markers = True, ci = 68, err_style='bars')

【问题讨论】:

    标签: pandas matplotlib seaborn plotly-python


    【解决方案1】:

    变体 1:使用子图并手动分离数据

    products = df['product'].unique()
    fig,ax = plt.subplots(1,len(products),figsize=(20,10))
    for i,p in enumerate(products):
        sns.lineplot('bought_date', 'Monthly_profit', data=df[df['product']==p], ax=ax[i])
        sns.lineplot('bought_date', 'Average_discout', data=df[df['product']==p], ax=ax[i].twinx(), color='orange')
        ax[i].legend([f'Product {p}'])
    

    变体 2:使用 FacetGrid:

    def lineplot2(x, y, y2, **kwargs):
        ax = sns.lineplot(x, y, **kwargs)
        ax2 = ax.twinx()
        sns.lineplot(x, y2, ax=ax2, **kwargs)
    
    g = sns.FacetGrid(df, col='product')
    g.map(lineplot2, 'bought_date', 'Monthly_profit', 'Average_discout', marker='o')
    

    这些只是一般的粗略示例,您必须根据需要整理轴标签等。

    【讨论】:

    • 我们可以为每个线图添加图例
    • ax[i].legend([f'Product {p}'])
    • 在哪一行,请帮我增加这个情节的大小。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2021-01-07
    相关资源
    最近更新 更多