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