I am just getting started with Pandas and using this data set, I managed to plot a line graph, with Purchase Date on the X axis and Price on the Y axis. However, I would like to plot the 'Apple' prices over time and the 'Orange' prices over time on the same graph, so there is one line for orange prices and one line for apple prices.
I've been looking up locs and grouping tutorials, but I've hit a bit of a brick wall in my learning, so any tips would be greatly appreciated.
This is the CSV file and my code so far.
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()
You can call the plot function twice to overlay the plots.
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()
Look here for further information on using.loc
Hope this helps.
You can use DataFrame.pivot_table with DataFrame.ffill , this way you can draw n graphics for n different fruits :
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.