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:
So the label of X-axis is shown as "Time". How can I show the time values in "Time" column on X-axis?
Matplotlib supports plots with time on the horizontal (x) axis. The data values will be put on the vertical (y) axis. In this article we'll demonstrate that using a few examples. It is required to use the Python datetime module, a standard module.
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.
You can do so:
df["Time"] = pd.to_datetime(df['Time'])
df.plot(x="Time", y=["Total cpu%", "process1 cpu%"])
plt.show()
Output:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With