I have the following data structure:
df = pd.DataFrame({"Date":["2015-02-02 14:19:00","2015-02-02 14:22:00","2015-02-17 14:57:00","2015-02-17 14:58:59"],"Occurrence":[1,0,1,1]})
df["Date"] = pd.to_datetime(df["Date"])
I want to plot the following:
import seaborn as sns
sns.set_theme(style="darkgrid")
sns.lineplot(x="Date", y="Occurrence", data=df)
And I get this:
I only want the hours and minutes to be shown on the x axis (the date of the day is unnecessary). How can I do that?
>Solution :
You can use the matplotlib
‘s Dateformatter
. Updated code and plot below. I did notice that the Date
column you posted had dates on 2nd and 17th. I changed those to show everything on the 2nd. Otherwise, there would be too many entries. Hope this helps…
df = pd.DataFrame({"Date":["2015-02-02 10:19:00","2015-02-02 12:22:00","2015-02-02 14:57:00","2015-02-02 16:58:59"],"Occurrence":[1,0,1,1]})
df["Date"] = pd.to_datetime(df["Date"])
import seaborn as sns
sns.set_theme(style="darkgrid")
ax = sns.lineplot(x="Date", y="Occurrence", data=df)
import matplotlib.dates as mdates
ax.xaxis.set_major_locator(mdates.HourLocator(interval=2))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
Output Plot