我刚开始使用Pandas,并使用此数据集,我设法绘制了一个折线图,在X轴上显示购买日期,在Y轴上显示价格。但是,我想在同一图表上绘制“苹果”价格随时间的变化和“橙色”价格随时间的变化,因此橙色价格有一条线,苹果价格有一条线。
我一直在查找位置和分组教程,但是我在学习中遇到了一些麻烦,因此任何提示都将不胜感激。
这是到目前为止的CSV文件和我的代码。
PurchaseDate, Fruit, Price
2019-01-05 08:00:00, Orange, 6
2019-01-06 08:00:00, Apple, 6
2019-01-07 08:00:00, Orange, 2
2019-01-08 08:00:00, Apple, 1
2019-01-09 08:00:00, Orange, 2
2019-01-10 08:00:00, Apple, 4
2019-01-11 08:00:00, Orange, 4
2019-01-12 08:00:00, Orange, 3
filename = 'fruit-data.csv'
fruits = pd.read_csv(filename)
plt.figure(figsize=(8,7))
plt.title('Purchase Date vs Price')
plt.plot(fruits.PurchaseDate, fruits.Price)
plt.xlabel('Time')
plt.ylabel('Price')
plt.show()
您可以调用两次绘图功能以覆盖绘图。
apple = fruits.loc[fruits.Fruit=='apple']
orange = fruits.loc[fruits.Fruit=='orange']
plt.figure(figsize=(8,7))
plt.title('Purchase Date vs Price')
plt.plot(apple.PurchaseDate, apple.Price)
plt.plot(orange.PurchaseDate, orange.Price)
plt.xlabel('Time')
plt.ylabel('Price')
plt.show()
查找here以获取有关使用.loc的更多信息
希望这会有所帮助。
您可以将DataFrame.pivot_table与DataFrame.ffill一起使用,这样您可以为n种不同的水果绘制n个图形:
prices_by_fruits=fruits.pivot_table(index='PurchaseDate',columns=' Fruit').ffill()
prices_by_fruits.columns=prices_by_fruits.columns.droplevel()
print(prices_by_fruits)
Fruit Apple Orange
PurchaseDate
2019-01-05 08:00:00 NaN 6.0
2019-01-06 08:00:00 6.0 6.0
2019-01-07 08:00:00 6.0 2.0
2019-01-08 08:00:00 1.0 2.0
2019-01-09 08:00:00 1.0 2.0
2019-01-10 08:00:00 4.0 2.0
2019-01-11 08:00:00 4.0 4.0
2019-01-12 08:00:00 4.0 3.0
prices_by_fruits.plot(figsize=(15,10))