【问题标题】:How to create a stacked line graph from one dataframe如何从一个数据框创建堆叠折线图
【发布时间】:2019-11-12 21:55:02
【问题描述】:

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

数据从 2019 年 1 月 1 日持续到 2019 年 10 月 31 日。我想分别绘制每个月(1 月、2 月、3 月、4 月……10 月)的图表。对于每个月,我想创建一个折线图,将 day_started 列与 num_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)

【问题讨论】:

  • 你能分享你的代码和一些测试数据吗?请参阅:minimal reproducible example
  • @AlexanderCécile 在我拥有的代码中进行了编辑。我正在使用 jupyter 笔记本
  • 样本/测试数据呢?它可以只是一个超级基本的例子。在不知道输入或无法运行的情况下推理代码基本上是不可能的。
  • print(df.head(10)) 并将其粘贴到您的图像位置。
  • @AlexanderCécile 我不确定如何上传整个 CSV。上图是我拨打df.head()时的视图。如果您看不到图片,请告诉我

标签: python pandas dataframe matplotlib seaborn


【解决方案1】:

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

输出

【讨论】:

    猜你喜欢
    • 2011-01-14
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多