How to set desired time interval and in desired format for X-Axis in line chart Python Matplotlib?

Viewed 584

input data Csv:[Csv data][1]

Need some help to correct below part of the code.

plt.xticks.set_major_locator(mdates.MinuteLocator(interval=10)) #to get a tick every 15 minutes plt.xticks.set_major_formatter(mdates.DateFormatter('%d-%H:%M')) #optional formatting

Code:

import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.read_csv("Data 8199 2391 6_6_2019 13_39_02.csv",sep="\t",skiprows=68,encoding = "utf-16",index_col=0)


#plt.xticks.set_major_locator(mdates.MinuteLocator(interval=10))   #to get a tick every 15 minutes
#plt.xticks.set_major_formatter(mdates.DateFormatter('%d-%H:%M'))     #optional formatting 
plt.yticks(np.arange(20, dfMax, step=5)) 

plt.show()
1 Answers

The functions set_major_formatter and set_major_locator are methods of an object Axis. In order to get the axes of the current figure, you can use the function plt.gca().


So, you could use the following code :

ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=10))
ax.xaxis.set_major_formatter(mdates.DateFormatter('D%d-%H:%M'))   

resulting in the following image :

enter image description here

(I used plt.xticks(rotation=30) in order to have the label slightly rotated.)

Related