Sumedh Junghare
Sumedh Junghare

Reputation: 391

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 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_axis = df["Time"].values

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

Following is the graph I could get so far: cpu usage graph

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

Upvotes: 10

Views: 44673

Answers (2)

Little Bobby Tables
Little Bobby Tables

Reputation: 4744

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.

Upvotes: 8

Joe
Joe

Reputation: 12417

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

Upvotes: 6

Related Questions