首页 > 解决方案 > Matplotlib:xmax 值和网格线

问题描述

我有一个用 Matplotlib 制作的情节。

X 值 - 时间

Y 值 - 数值数据

数据从 14:00 开始,到 15:00 结束。但绘图上的最后一个数据点不在 15:00 网格线上。

我尝试使用 set_xlim() 但这种方式带走了左右边距。我需要使绘图适合网格线并且我需要有左右边距。

有没有办法做到这一点?

这是我的代码和几张图片:

import matplotlib.pyplot as plt
import matplotlib.dates as pltdates
import os

timeValues = [737327.58333333, 737327.58402778, 737327.58472222, 737327.58541667, 737327.58611111, 737327.58680556, 737327.5875, 737327.58819444, 737327.58888889, 737327.58958333, 737327.59027778, 737327.59097222, 737327.59166667, 737327.59236111, 737327.59305556, 737327.59375, 737327.59444444, 737327.59513889, 737327.59583333, 737327.59652778, 737327.59722222, 737327.59791667, 737327.59861111, 737327.59930556, 737327.6, 737327.60069444, 737327.60138889, 737327.60208333, 737327.60277778, 737327.60347222, 737327.60416667, 737327.60486111, 737327.60555556, 737327.60625, 737327.60694444, 737327.60763889, 737327.60833333, 737327.60902778, 737327.60972222, 737327.61041667, 737327.61111111, 737327.61180556, 737327.6125, 737327.61319444, 737327.61388889, 737327.61458333, 737327.61527778, 737327.61597222, 737327.61666667, 737327.61736111, 737327.61805556, 737327.61875, 737327.61944444, 737327.62013889, 737327.62083333, 737327.62152778, 737327.62222222, 737327.62291667, 737327.62361111, 737327.62430556]
values = [74.3635, 74.3635, 74.3635, 74.3635, 74.3635, 74.3584, 74.3584, 74.3584, 74.3584, 74.3584, 74.3584, 74.3584, 74.3584, 74.3584, 74.3584, 74.3593, 74.3593, 74.3593, 74.3593, 74.3593, 74.3593, 74.3593, 74.3593, 74.3593, 74.3593, 74.3591, 74.3591, 74.3591, 74.3591, 74.3591, 74.3591, 74.3591, 74.3591, 74.3591, 74.3591, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3608, 74.3583, 74.3583, 74.3583, 74.3583]

myFmt = pltdates.DateFormatter('%H:%M')
xlocator = pltdates.MinuteLocator(byminute=[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55], interval=1)

fig = plt.figure(figsize=(20, 15))
ax = fig.add_subplot(1, 1, 1)
plt.grid(True, color='#efefef')
ax.xaxis.set_major_locator(xlocator)

# ax.set_xlim(min(timeValues), max(timeValues))
# ax.set_xbound(min(timeValues), max(timeValues))
# ax.margins(1, 1)

ax.plot(timeValues, values, color='green', linewidth=0.7)
ax.scatter(timeValues, values, c='green')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.subplots_adjust(top=0.95, bottom=0.05, left=0.05, right=0.95, hspace=0.2)

fileName = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'report.pdf')
plt.savefig(fileName, dpi=150)
plt.close()

剧情

问题

标签: pythonmatplotlib

解决方案


我不确定您的 timeValues-array 包含什么,但我认为这是几天?在这种情况下,您的 timeValues 数组中的最后一个值对应于 14:59:00 而不是 15:00:00:

>>> import datetime
>>> last_timeValue = 737327.62430556
>>> dayFraction =         0.62430556
>>> seconds = dayFraction * 60 * 60 * 24  # dayFraction * seconds in day
>>> print datetime.datetime.utcfromtimestamp(seconds)
1970-01-01 14:59:00.000384

推荐阅读