python - 如何从一个数据框创建堆叠折线图
问题描述
我有一个按月分组然后按日期分组的 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)
解决方案
您可以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')
推荐阅读
- c - 我正在尝试制作博物馆入口代码,但如果声明未反映,则可以同时比较字符串和整数
- laravel - 哪些图标支持安装在 laravel 8 应用程序中?
- amazon-web-services - AWS Pinpoint:分段数量是否会增加价格?
- java - 使用 Snap 重新安装后,启动时出现 PyCharm 错误“插件需要缺少‘Python’的类加载器”
- spring - 在静态方法中使用 Spring 存储库来设置测试数据
- html - 将自动生成的用于 python 代码的 Sphinx 嵌入到 html 页面中
- node.js - 在 Node 中使用 AutoML 模型进行图像分类
- javascript - 在本地存储中为边缘浏览器中的 URL 加载设置 KEY 和 Value
- python - 如何在不写入文件的情况下从数据框中获取 HTML?
- ios - Firebase 身份验证 - 检索 iOS 的自定义声明密钥