我如何绘制折线图,​​其中包含两家不同公司在前 12 个月和后 12 个月的月销售额

How can I plot a line chart with two different companies monthly sales from 12 months before and 12 months after

数据框是我正在使用的内容的快照。我想要实现的是不同品牌每月销售额的折线图。数字前带“-”的月份表示最多 12 个月之前的月份,数字前没有“-”的月份表示最多 12 个月之后的月份。在折线图上,所有“-”月份(之前的月份)都在左边,之后的月份在右边,以 0 为中心。 Count_Toy_Brand_A 是公司 A 中不同 Toy_Brands 的数量,而 Count_Toy_Brand_B 是公司 B 中不同 TOY_Brands 的数量。总共我将得到三个不同的A、B、C 的折线图,每条线都标记为公司 A 和公司 B。我想知道这是否可以在 pandas 中完成。任何帮助,将不胜感激。附件是我正在寻找的输出的快照。

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'toy_brand_A':['A', 'B', 'C'],
    'count_toy_brand_A':[11, 5, 16],
    'month-0_sales_A':[50, 12, 6],
    'month-1_sales_A':[8,7, 6],
    'month-2_sales_A':[8,7, 6],
    'month1_sales_A':[20, 40, 18],
    'month2_sales_A':[8,7, 6],
    'count_toy_brand_B':[15, 25, 4],
    'month-0_sales_B':[10, 8, 61],
    'month-1_sales_B':[3,5, 90],
    'month-2_sales_B':[4,7, 1],
    'month1_sales_B':[30, 20, 18],
    'month2_sales_B':[8,7, 6],
    })

先尝试重新格式化数据:

# Removes unnecessary columns and sets new indices.
cols = df.columns[~df.columns.str.contains('count')]
df = df[cols]
df.rename(columns={'toy_brand_A': 'toy_brand'}, inplace=True)
df.set_index('toy_brand', inplace=True)
df = df.T
df['company'] = 0
df.loc[df.index.str.contains('_A'), 'company'] = 'A'
df.loc[df.index.str.contains('_B'), 'company'] = 'B'
df.index = df.index.str.replace('_A', '')
df.index = df.index.str.replace('_B', '')

输出:

toy_brand       A   B   C   company
month-0_sales   50  12  6   A
month-1_sales   8   7   6   A
month-2_sales   8   7   6   A
month1_sales    20  40  18  A
month2_sales    8   7   6   A
month-0_sales   10  8   61  B

剧情:

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import pyplot as plt
plt.style.use('ggplot')


plt.figure(figsize=(10, 8))
for i, brand in enumerate(['A', 'B', 'C']):
    ax = plt.subplot(2, 2, i + 1)
    data = df[[brand, 'company']].reset_index()
    s = sns.lineplot(data=data, x='index', y=brand, hue='company', ax=ax)
    s.set_xticklabels(a.index, rotation=45, ha='right')
    s.set_xlabel('months', fontsize=20)
    s.set_ylabel(f'Sales brand {brand}', fontsize=20)
    s.set_title('My Title')
    
plt.tight_layout()
plt.show()