I try to figure a way out with pandas, where I can plot my data. First I want to group them by category, and then I want to group them by Model. In my Table I record the price on each day (timestamp).
And what I want to compare is, how the price change over time for the models, but within each category.
So I want a figure for Cars, Bikes, etc.., where I only plot the related price line
Example Table
# Timestamp Category Model Price
1 2020-05-01 Cars BMW M1 12000€
2 2020-05-01 Cars Audi A8 43000€
3 2020-05-01 Bikes Benelli 5000€
3 2020-05-01 Bikes Honda 9000€
At the moment, I do this:
df.groupby(['Category', 'Model' ]).plot(x = "Timestamp", y = "Price")
But this plots for each model a separet figure.
Can someone point me in the right direction?
[Edited]
I try to put make an python example, so you guys could get the data. In this example, we have stock price and Market Categories.
Basically, I want to plot the stock price of each company of category Q in one figure, and category O in another figure. And if there are more categories, plot the companies in other figures.
This way, you could compare one company of the same category against each other
import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
# import numpy as np
# import plotly
# import cufflinks as cf
import datetime
import yfinance as yf
# import time
import requests
import io
# cf.go_offline()
url="https://pkgstore.datahub.io/core/nasdaq-listings/nasdaq-listed_csv/data/7665719fb51081ba0bd834fde71ce822/nasdaq-listed_csv.csv"
s = requests.get(url).content
companies = pd.read_csv(io.StringIO(s.decode('utf-8')))[:5]
Symbols = companies['Symbol'].tolist()
Category = companies['Market Category'].tolist()
display(Symbols)
gr= companies.groupby('Market Category')
stock_final = pd.DataFrame()
# iterate over each symbol
start = datetime.datetime(2020,9,1)
end = datetime.datetime(2020,11,1)
for i in Symbols:
# print the symbol which is being downloaded
print( str(Symbols.index(i)) + str(' : ') + i, sep=',', end=',', flush=True)
index = Symbols.index(i)
try:
# download the stock price
stock = []
stock = yf.download(i,start=start, end=end, progress=False)
# append the individual stock prices
if len(stock) == 0:
None
else:
stock['Name']=i
stock['Market Category'] = Category[index]
stock_final = stock_final.append(stock,sort=False)
except Exception:
None
groups = stock_final.groupby(['Market Category', 'Name'])
groups.head()
Solution
I've ended up doing it in two for loops:
for name, group in df.groupby(['Market Category']):
fig, ax = plt.subplots()
for key, grp in group.groupby('Name'):
ax = grp.plot(ax=ax, kind='line', x='timestamp', y='price', label=key)
plt.title(name)
plt.legend(loc='best')
plt.show()