plot pandas数据框中的两列

2024-04-29 00:56:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,其中包含日期作为索引和一些列: 我想画一个有两条线的折线图(比如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   

Tags: 数据pandasdateammediareturnsdailyticker
3条回答

因此,以下代码从头开始创建一个与您的数据帧相似的数据帧,并生成您要求的绘图:

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()

enter image description here

但是,我相信您的数据帧在两个方面是不同的:

  1. 索引中似乎有两个级别(日期标题似乎位于Ticker标题的第二行)。我想这可能是因为您使用了诸如.groupby()或.unstack()或其他聚合/透视方法。我建议您查看reset_index()方法。

2.你的数据框有更多你需要的列。正如@jezrael所建议的,你应该首先只选择这些。你可以这样做:

df[['ISP.MI','Ctrv']]

然后在较小的数据帧上使用.plot()方法,让pandas处理其余部分。

我认为最简单的方法是按子集选择列,然后^{}

df[['ISP.MI','Ctrv']].plot()

如果您不关心轴刻度:

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-')

相关问题 更多 >