0

I am trying to plot temperature over time and use the datetime format for it. But when I plot it lines are obscurring the plot seemingly random. Maybe this is due to the cyclical nature of a year? Just a thought

  • here is the code:

the column df["DateTime"] is a datetime object.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

days = mdates.DayLocator()# every year
hours = mdates.HourLocator()# every month
days_fmt = mdates.DateFormatter('%D')



fig, ax = plt.subplots()

ax.minorticks_on()
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(days_fmt)
ax.xaxis.set_minor_locator(hours)

datemin = df['DateTime'].head(1)
datemax = df['DateTime'].tail(1)
ax.set_xlim(datemin, datemax)

ax.plot(df.DateTime, df.TempTop, label = 'Top')

ax.set_ylabel('Temperature in Celsius')

Plot produced by the code:

enter image description here

torakaou
  • 185
  • 1
  • 13
  • you should provide a minimal reproducible code. – snehil Jun 04 '20 at 15:30
  • probably your datetimes are not sorted, you have younger dates at the end of your dataframe – imbr Jun 04 '20 at 15:35
  • Your dtype of your 'DateTime' column is str or object. First, in your dataframe convert 'DateTime' to pandas datetime dtype. use `df['DateTime'] = pd.to_datetime(df['DateTime'])` – Scott Boston Jun 04 '20 at 16:11
  • You were right, about the datetimes not being sorted @Snehil. I am using pd.to_datetime, there seems to be a funny issue were it randomly switches day and month. As described here: https://stackoverflow.com/questions/50367656/python-pandas-pandas-to-datetime-is-switching-day-month-when-day-is-less-t Solution is to set dayfirst = True – torakaou Jun 04 '20 at 16:40

1 Answers1

0

the function

dfData.DateTime = pd.to_datetime(dfData['DateTime'])

was switching months and days at (to me it seems) random times.

Setting dayfirst=True:

pd.to_datetime(dfData['DateTime'], dayfirst=True)

resolved the issue.

Solution came from here:

Python Pandas : pandas.to_datetime() is switching day & month when day is less than 13

torakaou
  • 185
  • 1
  • 13