First time here? Checkout the FAQ!
x
+1 vote
229 views
asked in Python by (660 points)  

I have a dataframe like below

                    MT_001	    MT_002	    hour
2012-01-01 00:15:00	3.807107	22.759602	00:15:00
2012-01-01 00:30:00	5.076142	22.759602	00:30:00
2012-01-01 00:45:00	3.807107	22.759602	00:45:00
2012-01-01 01:00:00	3.807107	22.759602	01:00:00
2012-01-01 01:15:00	5.076142	22.048364	01:15:00

I can easily plot it using

data.plot()
plt.show()

However, this doesn't show the xlabel. What if i want to see the graph where the xlabel shows the ticks with 4 hours apart?

  

1 Answer

0 votes
answered by (115k points)  

Please take a look at the following code. I converted the data to time-series, and then showed how to resample it with a different frequency such 30 minutes. For 4 hours, change the first resample parameter to 4H

You can run the code here.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import io

data = """2012-01-01 00:15:00	3.807107	22.759602	00:15:00
2012-01-01 00:30:00	5.076142	22.759602	00:30:00
2012-01-01 00:45:00	3.807107	22.759602	00:45:00
2012-01-01 01:00:00	3.807107	22.759602	01:00:00
2012-01-01 01:15:00	5.076142	22.048364	01:15:00"""

df = pd.read_csv(io.StringIO(data), names =["date","time", "MT1", "MT2", "hour"], sep ="\s+")
df.drop(['hour'], axis = 1, inplace = True) #removing redundant hour


#Creating timestamp column by merging date and time
df["timestamp"] = (df["date"].map(str) + " " + df["time"])
df.index = pd.to_datetime(df["timestamp"])
df.drop(['date','timestamp'], axis = 1, inplace = True)
df2 = df.resample('30Min' ,base=0).last()
print("\ndf\n", df)
print("\ndf2\n",df2)

f, (ax1, ax2) = plt.subplots(1, 2,figsize=(20,5) )
ax1.plot(df['time'], df['MT1'],'ro--')
ax2.plot(df2['time'], df2['MT1'],'ro--')
ax1.plot(df['time'], df['MT2'],'bo--')
ax2.plot(df2['time'], df2['MT2'],'bo--')
ax1.grid(True)
ax2.grid(True)
ax1.legend()
ax2.legend()
plt.setp(ax1.xaxis.get_majorticklabels(), rotation=70, ha="right")
plt.setp(ax2.xaxis.get_majorticklabels(), rotation=70, ha="right")

plt.show()
plt.savefig('graph.png')

 

Related questions

+2 votes
2 answers 422 views
asked Oct 16, 2018 in Python by Neo (660 points)  
+1 vote
1 answer 13.7k views
...