我有一个pandas数据框,其中包含日期作为索引和一些列: 我想用2行绘制折线图(比如'ISP.MI'和'Ctrv');在x轴上我需要'日期'
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
答案 0 :(得分:25)
我认为最简单的是按子集选择列,然后是DataFrame.plot
:
df[['ISP.MI','Ctrv']].plot()
答案 1 :(得分:9)
如果您不关心轴刻度:
plt.figure()
x = df['Date']
y1 = df['ISP.MI']
y2 = df['Ctrv']
plt.plot(x,y1)
plt.plot(x,y2)
如果你关心它:
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-')
答案 2 :(得分:2)
所以,这是从头开始创建一个看起来像你的数据框并生成你要求的图的代码:
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()
但是,我认为您的数据框架有两种不同之处:
2.您的数据框有更多您需要的列。正如@jezrael所建议的,你应该首先选择这些。你可以这样做:
df[['ISP.MI','Ctrv']]
然后在较小的数据帧上使用.plot()方法,让pandas处理其余的数据。
答案 3 :(得分:0)
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()
答案 4 :(得分:0)
现在在最新的熊猫中,您可以直接使用df.plot.scatter函数
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
答案 5 :(得分:-1)