подзаголовки в python с несколькими линейными диаграммами с использованием pandas и seaborn

У меня есть кадр данных, как показано ниже

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')

person Danish    schedule 22.06.2020    source источник


Ответы (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')

Это всего лишь общие грубые примеры, вам придется привести в порядок метки осей и т. д. по мере необходимости.

person Stef    schedule 22.06.2020
comment
Можем ли мы добавить легенду для каждого линейного графика - person Danish; 22.06.2020
comment
в какой строке, пожалуйста, помогите мне увеличить размер этого графика. - person Danish; 22.06.2020