在Python/Matplotlib中,在x轴上将数据帧绘制为单日

在Python/Matplotlib中,在x轴上将数据帧绘制为单日,python,numpy,matplotlib,plot,pandas,Python,Numpy,Matplotlib,Plot,Pandas,我有这样的数据: col1 ;col2 2001-01-01;1 2001-01-01;2 2001-01-02;3 2001-01-03;4 2001-01-03;2 2001-01-04;2 fig, ax = plt.subplots() X = np.asarray(df['col1']).astype(DT.datetime) xfmt = mdates.DateFormatter('%b %d') ax.xaxis.set_major_formatter(xfmt) ax

我有这样的数据:

    col1  ;col2
2001-01-01;1
2001-01-01;2
2001-01-02;3
2001-01-03;4
2001-01-03;2
2001-01-04;2
fig, ax = plt.subplots()
X = np.asarray(df['col1']).astype(DT.datetime)
xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)
ax.plot(X, df['col2'])
plt.show()
    col1  ;col2 ; col3
2001-01-01;1;1
2001-01-01;2;1
2001-01-02;3;2
2001-01-03;4;3
2001-01-03;2;3
2001-01-04;2;4
.....
2001-02-01;2;32
我正在Python/Pandas中使用
pd阅读它。将_csv(…)
读入数据帧。 现在我想在y轴上绘制col2,在x轴上绘制col1。我搜索了很多,但找不到太多非常有用的页面详细描述这一点。我发现matplotlib当前不支持日期存储的数据格式(datetime64)

我试着这样转换它:

    col1  ;col2
2001-01-01;1
2001-01-01;2
2001-01-02;3
2001-01-03;4
2001-01-03;2
2001-01-04;2
fig, ax = plt.subplots()
X = np.asarray(df['col1']).astype(DT.datetime)
xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)
ax.plot(X, df['col2'])
plt.show()
    col1  ;col2 ; col3
2001-01-01;1;1
2001-01-01;2;1
2001-01-02;3;2
2001-01-03;4;3
2001-01-03;2;3
2001-01-04;2;4
.....
2001-02-01;2;32
但这是行不通的。 最好的方法是什么? 我只能在那里找到点点滴滴,但没有任何东西能够真正完整地工作,更重要的是,最新版本的pandas/numpy/matplotlib提供了与此功能相关的最新资源

我还想将绝对日期转换为连续日指数,即: 开始日期2001-01-01是第1天,因此数据如下所示:

    col1  ;col2
2001-01-01;1
2001-01-01;2
2001-01-02;3
2001-01-03;4
2001-01-03;2
2001-01-04;2
fig, ax = plt.subplots()
X = np.asarray(df['col1']).astype(DT.datetime)
xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)
ax.plot(X, df['col2'])
plt.show()
    col1  ;col2 ; col3
2001-01-01;1;1
2001-01-01;2;1
2001-01-02;3;2
2001-01-03;4;3
2001-01-03;2;3
2001-01-04;2;4
.....
2001-02-01;2;32

非常感谢。

好的,据我所知,不再需要直接使用
matplotlib
,但熊猫本身已经提供了绘图功能,可以用作数据框对象的方法,请参阅。这些函数本身使用matplotlib,但更易于使用,因为它们自己正确处理数据类型:-)

Pandas.read\u csv支持parse\u dates=True(当然默认值为False),这将节省您单独转换日期的时间

同样对于这样一个简单的数据帧,pandas plot()函数也能很好地工作。 例如: