Search code examples
pythondatetimeseabornstrftime

Unable to set custom timestamp xticks in seaborn lineplot [python]


My dataframe looks like this: enter image description here

We see category values for a given Date/Time timestamp, showing year, month, day, and the time.

Plotted as a lineplot in seaborn, the x-axis looks like this: enter image description here

Here we see the Date/Time x-axis tick marks showing the month, day, and hour.

What I am trying to accomplish is to have the Date/Time x-tick marks reformatted to just show the time, so starting at 00:00, with 6 total tick marks, and so for the whole study day, continuing with 04:00, 08:00, 12:00, 16:00, 20:00, 00:00.

I tried using this code to reset the date/time format:

x_dates = df['Date/Time'].dt.strftime('%H:%M').sort_values().unique()
dataplot.set_xticklabels(labels=x_dates, rotation=45, ha='right')

And now my x-axis ticks look like this: enter image description here

I do not understand why the hours go from 00:30 to 04:30. That means that my study only lasted until 4:30PM? I do not know if this is supposed to be military time or not. My study data lasts for 24 hours, so I do not understand why this code changes the data to end at 04:30.

And then I try to change the number of x-axis tick marks to 6 by adding:

dataplot.set_xticks(6)

But this just results in this error:

TypeError: object of type 'int' has no len()

How can I fix my date/time string formatting for my x-ticks so that it just shows the time throughout the 24-hour period, without the year, month, or day, and as 6-tick marks? I am using seaborn with Python.


Solution

  • You only have 9 xticks, so what you are doing in your code is replacing these with the first 9 values of your x_dates. Seaborn doesn't know how the x_dates relate to the plot you made, so it just takes the first 9 values.

    If each study runs for exactly one day, the easiest way to solve this woudl be to create a new column containing just the time, then plot using that column.

    df['time'] = df['Date/Time'].dt.strftime('%H:%M')