[英]How do I change the range of the x-axis with datetimes in matplotlib?
我試圖在 x 軸上繪制日期圖,在 y 軸上繪制值。 它工作正常,除了我無法獲得合適的 x 軸范圍。 盡管我的日期是從今天開始,但 x 軸范圍始終是 2012 年 1 月到 2016 年 1 月。 我什至指定 xlim 應該是第一個和最后一個日期。
如果相關,我正在為 python-django 寫這個。
import datetime
import matplotlib.pyplot as plt
x = [datetime.date(2014, 1, 29), datetime.date(2014, 1, 29), datetime.date(2014, 1, 29)]
y = [2, 4, 1]
fig, ax = plt.subplots()
ax.plot_date(x, y)
ax.set_xlim([x[0], x[-1]])
canvas = FigureCanvas(plt.figure(1))
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
這是輸出:
從 OP 看到實際數據后,所有值都在同一日期/時間。 所以 matplotlib 會自動縮小 x 軸。 您仍然可以使用datetime
對象手動設置 x 軸限制
如果我在 matplotlib v1.3.1 上做這樣的事情:
import datetime
import matplotlib.pyplot as plt
x = [datetime.date(2014, 1, 29)] * 3
y = [2, 4, 1]
fig, ax = plt.subplots()
ax.plot_date(x, y, markerfacecolor='CornflowerBlue', markeredgecolor='white')
fig.autofmt_xdate()
ax.set_xlim([datetime.date(2014, 1, 26), datetime.date(2014, 2, 1)])
ax.set_ylim([0, 5])
我得到:
軸限制與我指定的日期相匹配。
在 Paul H 的解決方案的幫助下,我能夠更改基於時間的 x 軸的范圍。
這是其他初學者的更通用的解決方案。
import matplotlib.pyplot as plt
import datetime as dt
# Set X range. Using left and right variables makes it easy to change the range.
#
left = dt.date(2020, 3, 15)
right = dt.date(2020, 7, 15)
# Create scatter plot of Positive Cases
#
plt.scatter(
x, y, c="blue", edgecolor="black",
linewidths=1, marker = "o", alpha = 0.8, label="Total Positive Tested"
)
# Format the date into months & days
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
# Change the tick interval
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=30))
# Puts x-axis labels on an angle
plt.gca().xaxis.set_tick_params(rotation = 30)
# Changes x-axis range
plt.gca().set_xbound(left, right)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.