首页 > 解决方案 > 如何从一个数据框创建堆叠折线图

问题描述

我有一个按月分组然后按日期分组的 csv 文件。

数据从 2019 年 1 月 1 日持续到 2019 年 10 月 31 日。我想分别绘制每个月(1 月、2 月、3 月、4 月...... 10 月)的图表。对于每个月,我想创建一个折线图,将day_startednum_orders列进行比较。

我已将 csv 加载到数据框中df = pd.read_csv('orders.csv')

如果我用 seaborn 创建了一个线图plot = sns.lineplot(x='month', y='num_orders', data=df),它会将所有月份绘制在一起,但我想根据月份创建 10 个单独的线图。请让我知道我是否可以进一步扩展。

编辑:我有的代码:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
%matplotlib inline

df = pd.read_csv('orders.csv')

plot = sns.lineplot(x='month', y='num_orders', data=df)

编辑 (2) 在此处输入图像描述

标签: pythonpandasdataframematplotlibseaborn

解决方案


您可以hue=month在 sns.lineplot(...) 中使用。您还必须从中提取 day day_started,然后 make x=day。否则绘图x=day_started意味着您正在绘制单独和不连续的线。

这是一个简短的示例,其中包含一个示例数据框来指导您。

代码

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

month = [1,1,1,1,1,\
         2,2,2,2,2,\
         3,3,3,3,3]

day_started = ['2019-01-01','2019-01-07','2019-01-05','2019-01-11','2019-01-31',\
              '2019-02-28','2019-02-17','2019-02-13','2019-02-10','2019-02-07',\
              '2019-03-04','2019-03-07','2019-03-15','2019-03-23','2019-03-18']

num_order = [1,4,5,6,7,\
            8,9,10,4,2,\
            5,6,9,1,3]

data = {'month':month,'day_started':pd.to_datetime(day_started),'num_order':num_order}

df = pd.DataFrame(data)

df['day'] = df['day_started'].apply(lambda t: t.day)

#print(df)
#at this stage the df looks like this

#     month day_started  num_order  day
# 0       1  2019-01-01          1    1
# 1       1  2019-01-07          4    7
# 2       1  2019-01-05          5    5
# 3       1  2019-01-11          6   11
# 4       1  2019-01-31          7   31
# 5       2  2019-02-28          8   28
# 6       2  2019-02-17          9   17
# 7       2  2019-02-13         10   13
# 8       2  2019-02-10          4   10
# 9       2  2019-02-07          2    7
# 10      3  2019-03-04          5    4
# 11      3  2019-03-07          6    7
# 12      3  2019-03-15          9   15
# 13      3  2019-03-23          1   23
# 14      3  2019-03-18          3   18

plt.figure(figsize=(12,8))
sns.lineplot(x='day',y='num_order',hue='month',data=df,legend='full')

输出 在此处输入图像描述


推荐阅读