How to plot `datetime.time` type on an axis?

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>TypeError: float() argument must be a string or a real number, not 'datetime.time'
</code>
<code>TypeError: float() argument must be a string or a real number, not 'datetime.time' </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># convert df.index from datetime.datetime to datetime.time type
# and aggregate values using groupby
new_df = df.groupby(df.index.time).sum()
</code>
<code># convert df.index from datetime.datetime to datetime.time type # and aggregate values using groupby new_df = df.groupby(df.index.time).sum() </code>
# 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>print(df["Datetime"].dtype)
# object
</code>
<code>print(df["Datetime"].dtype) # object </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật