我尝试运行代码:
fig, ax = plt.subplots()
ax.plot(x, y, color="g")
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y'))
hlines=[40,50]
ax.hlines(hlines, 1, len(x), color='g')
plt.show()
Run Code Online (Sandbox Code Playgroud)
我希望它能画出这样的东西:
画图表没问题,可以,但是画水平线不行。
当我运行我的代码时,它会绘制:
PS x 是这样创建的:日期到 matplotlib 日期
x.append(matplotlib.dates.date2num(datetime.strptime(date, '%Y%m%d')))
Run Code Online (Sandbox Code Playgroud)
You are drawing a horizontal line from x-axis=1
to x-axis=len(x)
, which are just arbitrary integers that does not represent anything on your graph: your x-axis is much larger because you use matplotlib.dates.date2num
. You need to properly assign the range for your horizontal line. For example:
ax.hlines(hlines, min(x), max(x), color='g')
Run Code Online (Sandbox Code Playgroud)
or
ax.hlines(hlines,
matplotlib.dates.date2num(datetime.strptime(mindate, '%Y%m%d')),
matplotlib.dates.date2num(datetime.strptime(maxdate, '%Y%m%d')),
color='g')
Run Code Online (Sandbox Code Playgroud)
or you could just use axhline
:
ax.axhline(40, color='g')
ax.axhline(50, color='g')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6456 次 |
最近记录: |