如何使用matplotlib在日期时间轴上绘制矩形? [英] How to plot a rectangle on a datetime axis using matplotlib?

查看:62
本文介绍了如何使用matplotlib在日期时间轴上绘制矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码在具有日期时间x轴的图形上绘制矩形:

I tried to plot a rectangle on a graph with a datetime x-axis using the following code:

from datetime import datetime, timedelta
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt

# Create new plot
fig = plt.figure()
ax = fig.add_subplot(111)

# Create rectangle
startTime = datetime.now()
width = timedelta(seconds = 1)
endTime = startTime + width
rect = Rectangle((startTime, 0), width, 1, color='yellow')

# Plot rectangle
ax.add_patch(rect)   ### ERROR HERE!!! ###
plt.xlim([startTime, endTime])
plt.ylim([0, 1])
plt.show()

但是,我得到了错误:

TypeError: unsupported operand type(s) for +: 'float' and 'datetime.timedelta'

出了什么问题?(我使用的是 matplotlib 1.0.1 版)

What's going wrong? (I'm using matplotlib version 1.0.1)

推荐答案

问题在于 matplotlib 使用自己的日期/时间表示(浮动天数),因此您必须先转换它们.此外,您将不得不告诉xaxis它应该具有日期/时间刻度和标签.下面的代码就是这样做的:

The problem is that matplotlib uses its own representation of dates/times (floating number of days), so you have to convert them first. Furthermore, you will have to tell the xaxis that it should have date/time ticks and labels. The code below does that:

from datetime import datetime, timedelta
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Create new plot
fig = plt.figure()
ax = fig.add_subplot(111)

# Create rectangle x coordinates
startTime = datetime.now()
endTime = startTime + timedelta(seconds = 1)

# convert to matplotlib date representation
start = mdates.date2num(startTime)
end = mdates.date2num(endTime)
width = end - start

# Plot rectangle
rect = Rectangle((start, 0), width, 1, color='yellow')
ax.add_patch(rect)   

# assign date locator / formatter to the x-axis to get proper labels
locator = mdates.AutoDateLocator(minticks=3)
formatter = mdates.AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

# set the limits
plt.xlim([start-width, end+width])
plt.ylim([-.5, 1.5])

# go
plt.show()

结果:

注意:Matplotlib 1.0.1 非常很旧.我不能保证我的例子会奏效.你应该尝试更新!

NOTE: Matplotlib 1.0.1 is very old. I can't guarantee that my example will work. You should try to update!

这篇关于如何使用matplotlib在日期时间轴上绘制矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆