如何在 pandas 中将时间绘制为 x 轴 [英] How to plot time as x axis in pandas

查看:75
本文介绍了如何在 pandas 中将时间绘制为 x 轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Pandas 中绘制数据框.我使用的 csv 文件是:

I am trying to plot a data-frame in pandas. The csv file I am using is:

Time,Total cpu%,Used mem(k),Cache mem(k),Net mem Used%,Total mem Used%,Swap mem(%),process1 cpu%,process1 mem%,
4:19:25,12.5,885324,1249960,38.38,38.38,0,6.2,34.7
4:19:28,0.4,885460,1249804,38.39,38.39,0,5.3,34.7
4:19:31,1.8,885700,1249528,38.4,38.4,0,5,34.7
4:19:34,0.7,885700,1249528,38.4,38.4,0,5.3,34.7
4:19:37,0.4,885708,1249528,38.4,38.4,0,5.3,34.7
4:19:40,2.1,885704,1249528,38.4,38.4,0,5.3,34.7
4:19:43,0.4,885704,1249528,38.4,38.4,0,5,34.7
4:19:47,0.7,885700,1249528,38.4,38.4,0,5.3,34.7
4:19:50,13.8,885704,1249528,38.4,38.4,0,16,34.7

到目前为止我的代码是:

My code so far is:

import pandas as pd
import matplotlib.pyplot as plt

# create dataframe
df = pd.read_csv('sample_csv.csv')

# select only cpu columns
cpu_columns = ['Total cpu%', 'process1 cpu%']

# dataframe from cpu columns
df1 = df[cpu_columns]

我想用 X 轴上的所有时间值绘制此数据框.所以我从时间"列中的值创建了一个列表,并将其设置为 x_axis 值,如下所示:

I want to plot this data-frame with all the time values on X-axis. So I created a list from values in "Time" column and set it as x_axis value as follows:

x_axis = df["Time"].values

# plot dataframe
df1.plot(x=df["Time"])
plt.show()

以下是我目前得到的图表:

Following is the graph I could get so far:

所以X轴的标签显示为时间".如何在 X 轴的时间"列中显示时间值?

So the label of X-axis is shown as "Time". How can I show the time values in "Time" column on X-axis?

推荐答案

看来您的问题可能与您的时间存储方式有关.如果它们是 timedatetime dtypes,那么以下应该很适合你.

It seems that your issue might be to do with the way your times are stored. If they are of time or datetime dtypes then the following should work nicely for you.

将时间设置为索引并简单地调用 plot.Pandas 默认设置索引为 x 轴.

Set Time as the index and simply call plot. Pandas sets the index as the x-axis by default.

df.Time = df.Time.dt.time
df.set_index('Time').plot()

但是,从代码的外观来看,它们并非如此.我们可以先将这些作为日期时间传递,然后将它们转换为时间(如果需要).这可以使用 pd.to_datetime 来完成,如下所示,

However, by the looks of your code, they are not. We can pass these as datetimes first, and then convert them to times (if needed). This can be done using pd.to_datetime as follows,

df.Time = pd.to_datetime(df.Time).dt.time
df.set_index('Time').plot()

注意:这将默认使用今天的日期添加到日期时间.但是,当转换为 Time dtype 时,它​​会被删除.

Note: This will default to using today's date to add to the datetime. However this is then dropped when converting to a Time dtype.

这篇关于如何在 pandas 中将时间绘制为 x 轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆