Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I only plot hours and minutes in seaborn?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading