python - matplotlib:使用 matplotlib 或 seaborn 显示每个日期的所有产品价格的折线图
问题描述
如何使用折线图在一张图表中显示每个日期的所有产品价格?
数据框有三列,就像:
+---------+-------+----------+
| product | price | date |
+---------+-------+----------+
| pen | 1 | 20190101 |
| apple | 2 | 20190101 |
| book | 3 | 20190101 |
| cup | 4 | 20190101 |
| pen | 0.8 | 20190102 |
| apple | 2.2 | 20190102 |
| book | 3.1 | 20190102 |
| cup | 3.5 | 20190102 |
| pen | 0.6 | 20190103 |
| apple | 2.6 | 20190103 |
| book | 2.1 | 20190103 |
| cup | 4.3 | 20190103 |
+---------+-------+----------+
解决方案
假设您的数据框:
import pandas as pd
df = pd.DataFrame({'product':['pen','apple','book','cup','pen','apple','book','cup','pen','apple','book','cup',],
'price':[1,2,3,4,0.8,2.2,3.1,3.5,.6,2.6,2.1,4.3],
'date':['20190101','20190101','20190101','20190101','20190102','20190102','20190102','20190102','20190103','20190103','20190103','20190103']})
您可以使用pandas.DataFrame.groupby
对产品进行分组并matplotlib
绘制每种产品的价格:
import matplotlib.pyplot as plt
for i in df.groupby('product'):
plt.plot(i[1].date,i[1].price,'-o',label=i[0])
plt.legend(loc='upper center',
bbox_to_anchor=(0.5, -0.2),
fancybox=True,
shadow=True,
ncol=4)
plt.xlabel('date')
plt.ylabel('price')
plt.show()
推荐阅读
- c# - 检查一个类是否实现了一个精确的泛型类定义
- javascript - JS 表单事件和验证
- css - Chrome 中的 Flexbox 高度损坏
- java - 如何使用 Apache MINA SSHD 阻止 SFTP 删除操作
- bash - 计算 git 存储库给定分支中所有文件的所有行的出现总数
- react-native - 我在异步函数中得到`Can not use keyword 'await' outside async function` .. React-native
- java - java中的回文,要求用户输入不同的输入直到他们进入停止,该方法应该删除所有空格并使字母小写
- python - django查询访问外键数据
- java - 手动输入 JDatePicker 对象时出错?
- r - NextMethod 中的错误(“[<-”):数组中不正确的订阅数