Reputation: 213
i have a pandas dataframe which has dates as indexes and some columns: I would like to plot a line chart with 2 lines (let's say 'ISP.MI' and 'Ctrv'); on the x axis I need the 'Date'
Ticker ISP.MI Daily returns Ctrv Inv_Am Giac_Media
Date
2016-01-01 2.90117 NaN 100.000000 100 100.0
2016-01-04 2.80159 -0.034927 196.507301 200 150.0
2016-01-05 2.85608 0.019263 300.292610 300 200.0
2016-01-06 2.77904 -0.027345 392.081255 400 250.0
2016-01-07 2.73206 -0.017050 485.396411 500 300.0
2016-01-08 2.72267 -0.003443 583.725246 600 350.0
Upvotes: 21
Views: 106596
Reputation: 2177
Now in latest pandas you can directly use df.plot.scatter function
df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
[6.4, 3.2, 1], [5.9, 3.0, 2]],
columns=['length', 'width', 'species'])
ax1 = df.plot.scatter(x='length',
y='width',
c='DarkBlue')
https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.scatter.html
Upvotes: 0
Reputation: 1398
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
d = {'x' : [1,2,3,4,5,6,7,8,9,10],
'y_one' : np.random.rand(10),
'y_two' : np.random.rand(10)}
df = pd.DataFrame(d)
df.plot('x',y=['y_one','y_two'])
plt.show()
Upvotes: 18
Reputation: 771
So, here is the code that from scratch creates a dataframe that looks like yours and generates the plot you asked for:
import pandas as pd
import datetime
import numpy as np
from matplotlib import pyplot as plt
# The following two lines are not mandatory for the code to work
import matplotlib.style as style
style.use('dark_background')
def create_datetime_range(numdays=10):
"""Creates the timestamp range"""
base = datetime.datetime.today()
datelist = pd.date_range(base, periods=numdays).to_pydatetime()
return datelist
def convert_to_date(datetime_list):
"""Converts a timestamp array into a date array"""
return [x.date() for x in datetime_list]
a = pd.DataFrame(
{
'ISP.MI': np.random.normal(2,1,10),
'Ctrv' : np.random.normal(200,150,10)
},
index=convert_to_date(create_date_range())
)
a.plot()
However, I believe that your dataframe is different in two ways:
2.Your dataframe has more columns that you need. As suggested by @jezrael, you should first select only these. You can do it with something like:
df[['ISP.MI','Ctrv']]
and then using the .plot() method on the smaller dataframe and let pandas handle the rest.
Upvotes: 2
Reputation: 863611
I think the simpliest is select columns by subset and then DataFrame.plot
:
df[['ISP.MI','Ctrv']].plot()
Upvotes: 56
Reputation: 2448
if you dont care about axis scale:
plt.figure()
x = df['Date']
y1 = df['ISP.MI']
y2 = df['Ctrv']
plt.plot(x,y1)
plt.plot(x,y2)
if you do care about it:
fig, ax1 = plt.subplots()
x = df['Date']
y1 = df['ISP.MI']
y2 = df['Ctrv']
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
Upvotes: 17