繁体   English   中英

如何从一个 dataframe 创建堆叠折线图

[英]How to create a stacked line graph from one dataframe

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

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

我已使用df = pd.read_csv('orders.csv')将 csv 加载到 dataframe 中

if I created a line plot with seaborn plot = sns.lineplot(x='month', y='num_orders', data=df) , it graphs all months together, but I wanted to create 10 separate line graphs based on the month . 请让我知道我是否可以进一步扩展。

编辑:我有的代码:

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) 在此处输入图像描述

您可以在 sns.lineplot(...) 中使用hue=month 您还必须从day_started中提取 day ,然后制作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')

Output 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM