Skip to content Skip to sidebar Skip to footer

How To Plot Time As X Axis In Pandas

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 me

Solution 1:

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.

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

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

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.


Solution 2:

You can do so:

df["Time"] = pd.to_datetime(df['Time'])
df.plot(x="Time", y=["Total cpu%", "process1 cpu%"])
plt.show()

Output: enter image description here


Post a Comment for "How To Plot Time As X Axis In Pandas"