0
我想绘制一个矩形来指示x轴内的范围。我可以使用定位器设置刻度和标签,但我似乎没有成功使用它们绘制矩形。我怎么能去呢?!在日期轴上对齐矩形
import datetime as DT
from matplotlib import pyplot as plt
import matplotlib.dates as dates
ddata = [DT.datetime.strptime('2010-02-05', "%Y-%m-%d"),
DT.datetime.strptime('2010-02-19', "%Y-%m-%d"),
DT.datetime.strptime('2010-03-05', "%Y-%m-%d"),
DT.datetime.strptime('2010-03-19', "%Y-%m-%d"),]
values = [123,678,987,345]
d1 = zip(ddata,values)
def nplot(data):
x = [date for (date, value) in data]
y = [value for (date, value) in data]
# Set the stage
fig, ax = plt.subplots()
graph = fig.add_subplot(111)
# Plot the data as a red line with round markers
graph.plot(x,y,'r-o')
days = dates.DayLocator(interval=7) # every week
months = dates.MonthLocator() # every month
# Create locators and ticks
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d'))
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n%b'))
ax.xaxis.grid(True, which="major", linewidth=2)
# Now how do I align a rectangle with specific dates?
gca().add_patch(Rectangle((data[0][0], 1000),
data[2][0], 1000, facecolor='w', alpha=0.9)) # doesn't work
plt.show()
nplot(d1)
你的代码已经提供了很多细节,但它不完全清楚(至少对我来说)问题是什么。我怀疑[这里的第三个演示](http://matplotlib.org/examples/pylab_examples/fill_between_demo.html)会帮助你。 – Greg
@Greg,可能吧,我明天再试。我的例子没有显示它(因为我不知道该怎么做),但是我想在每个第二对日期定位器之间填充。最终,我想填补季度(1月至3月,然后7月至9月等),无论轴限制在哪里。并且为了填补它,我希望填充的边界在月份之间,因此很清楚哪些月属于本季度。不要问太多? :) – dmvianna