I am trying to plot a dataframe which has a datetime.time
index type.
Matplotlib does not appear to support plotting an axis using a datetime.time
type, and attempting to do so produces the following error message:
TypeError: float() argument must be a string or a real number, not 'datetime.time'
The data I am working with looks at events which occur during a day. The data is a datetime.time
type and not a datetime.datetime
type, because conceptually events occur across multiple dates, and only the time of day is important.
The data is created by aggregating what was a datetime.datetime
index:
# convert df.index from datetime.datetime to datetime.time type
# and aggregate values using groupby
new_df = df.groupby(df.index.time).sum()
There are a large number of unique time values (60 minutes * 24 hours = 1,440 unique values). This means that the usual suggestion of converting to str
will not work.
Converting to str
is the wrong thing to do anyway, because datetime.time
types are not strings, and if we convert them to strings just to plot a figure, we then lose the ability to perform further operations on the data, unless we convert the values back into time values by parsing them. It’s just not the right solution.
What is the real solution to this problem?
9
I’ll just post this example for others who might be facing the same problem and would like to get nice x ticks when plotting with datetime on the x-axis.
I have here an example of a dataframe that I read from excel with the following form:
We read this into python with pandas: df = pd.read_excel("exampleForStack.xlsx")
Now that we have this here, let’s see what the datatype of the “Datetime” column is:
print(df["Datetime"].dtype)
# object
We confirm that it is an object, in this case, plotting the values will look like this:
To mitigate this, we can convert the column to datetime by using: df["Datetime"] = pd.to_datetime(df["Datetime"])
Plotting again, this gives us:
This is “correct” in a sense, but the values are ugly and not visible in some cases. This is where the following code can be used to make very nice xticklabels automatically:
plt.figure()
plt.plot(df["Datetime"], df["Values"])
plt.grid()
plt.xlabel("Datetime")
plt.ylabel("Values")
locator = mdates.AutoDateLocator(minticks = 5, maxticks = 7)
formatter = mdates.ConciseDateFormatter(locator)
plt.gca().xaxis.set_major_locator(locator)
plt.gca().xaxis.set_major_formatter(formatter)
The above plot shows nice xticks, this comes from the matplotlib.dates
package. In my code, I import this package as mdates
Hope this helps you further!
2