pandas 如何在熊猫中将时间绘制为 x 轴
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51556953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to plot time as x axis in pandas
提问by Sumedh Junghare
I am trying to plot a data-frame in pandas. The csv file I am using is:
我正在尝试在Pandas中绘制一个数据框。我使用的 csv 文件是:
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]
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 轴上的所有时间值绘制这个数据框。因此,我从“时间”列中的值创建了一个列表,并将其设置为 x_axis 值,如下所示:
x_axis = df["Time"].values
# plot dataframe
df1.plot(x=df["Time"])
plt.show()
Following is the graph I could get so far:
So the label of X-axis is shown as "Time". How can I show the time values in "Time" column on X-axis?
所以X轴的标签显示为“时间”。如何在 X 轴的“时间”列中显示时间值?
回答by Little Bobby Tables
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.
您的问题似乎与您的时间存储方式有关。如果它们是 oftime
或datetime
dtypes,那么以下内容应该很适合您。
Set Time as the index and simply call plot. Pandas sets the index as the x-axis by default.
将时间设置为索引并简单地调用 plot。Pandas 默认将索引设置为 x 轴。
df.Time = df.Time.dt.time
df.set_index('Time').plot()
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,
但是,从您的代码的外观来看,它们并非如此。我们可以先将这些作为日期时间传递,然后将它们转换为时间(如果需要)。这可以使用pd.to_datetime
如下完成,
df.Time = pd.to_datetime(df.Time).dt.time
df.set_index('Time').plot()
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.
注意:这将默认使用今天的日期添加到日期时间。但是,当转换为 Time dtype 时,它会被删除。