pythonmatplotlib绘制折线图x轴时间如何设置_python-
matplotl。。。
我正在尝试在天⽓数据图中格式化x轴.我对y轴感到满意,但是到⽬前为⽌,我为使x轴成为⼀种体⾯的,⼈类可读的格式所做的所有尝试都没有奏效.因此,经过数⼩时的反复试验,希望能对您有所帮助.
matplotlib中subplot
我正在努⼒实现的⽬标
最后,我希望每30分钟就有⼀个刻度线,每⼩时有⼀个垂直的虚线⽹格线,其下⽅写有HH:MM的时间,另外还有每天晚上00:00点写的⽇期.诸如此类(注意,前⾯的ASCII艺术不好!):
: : :
: : :
: : :
: : :
: : :
|====|====|====|====|====|====|====
23:00 00:00 01:00
09JAN18
所有时间都是UTC,这将是最终的豪华版本.但是我的问题是从更早开始的.
我的代码段
⾸先,我尝试将其转换为可读的格式.我想出了
locator = mdates.AutoDateLocator()
希望我能摆脱经验
结果
输出不完全是我希望的:
[email protected]:~/wx-logging $python plot.py
[( 15.94, 57.86, 992.65, 1019.99, 1515460740)
( 15.96, 57.8 , 992.65, 1019.99, 1515460745)
( 15.99, 57.79, 992.68, 1020.02, 1515460750) ...,
( 13.25, 55.7 , 990.16, 1017.43, 1515496060)
( 13.31, 56. , 990.14, 1017.41, 1515496065)
( 13.34, 56.32, 990.13, 1017.4 , 1515496070)]
Traceback (most recent call last):
File "plot.py", line 123, in
plt.savefig("plot.png", dpi=150)
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 697, in savefig
res = fig.savefig(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/figure.py", line 1572, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 2244, in print_figure
**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 545, in print_png FigureCanvasAgg.draw(self)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 464, in draw
self.figure.derer)
File "/usr/lib/python2.7/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/figure.py", line 1143, in draw
renderer, self, dsu, self.suppressComposite)
File "/usr/lib/python2.7/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images a.draw(renderer)
File "/usr/lib/python2.7/dist-packages/mpl_toolkits/axes_grid1/parasite_axes.py", line 295, in draw self._get_base_axes_attr("draw")(self, renderer)
File "/usr/lib/python2.7/dist-packages/mpl_toolkits/axisartist/axislines.py", line 778, in draw
super(Axes, self).draw(renderer, inframe)
File "/usr/lib/python2.7/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2409, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/usr/lib/python2.7/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images a.draw(renderer)
File "/usr/lib/python2.7/dist-packages/mpl_toolkits/axisartist/axis_artist.py", line 915, in draw
gl = self.__gridlines(self._which, self._axis)
File "/usr/lib/python2.7/dist-packages/mpl_toolkits/axisartist/axislines.py", line 546, in get_d(self.axes.xaxis.major.locator())
File "/usr/lib/python2.7/dist-packages/matplotlib/dates.py", line 983, in __call__
File "/usr/lib/python2.7/dist-packages/matplotlib/dates.py", line 1003, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/usr/lib/python2.7/dist-packages/matplotlib/dates.py", line 760, in viewlim_to_dt
return num2date(vmin, ), num2date(vmax, )
File "/usr/lib/python2.7/dist-packages/matplotlib/dates.py", line 401, in num2date
return _from_ordinalf(x, tz)
File "/usr/lib/python2.7/dist-packages/matplotlib/dates.py", line 254, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: year is out of range
[email protected]:~/wx-logging $
并不完全有希望.我不知道为什么会说ValueError:year超出范围,因为它是unix时代的时间戳.
我究竟做错了什么?如何获得上⾯概述的预期结果?我⾮常感谢朝着正确⽅向前进.谢谢您的帮助!
祝⼀切顺利,
克⾥斯
完整的脚本
为了给您⼀些背景,到⽬前为⽌我完整的脚本.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('AGG')
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as aa
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FuncFormatter
import numpy as np
from numpy import vectorize
import datetime
import shutil
import math
# Dewpoint calculation
def dewpoint(tempC, rlHum):
r = 8314.3
mw = 18.016
if tempC >= 0:
a = 7.5
b = 237.3
# over water:
# elif tempC < 0:
# a = 7.6
# b = 240.7
#
# over ice:
elif tempC < 0:
a = 9.5
b = 265.5
saettDampfDruck = 6.1078 * 10**((a*tempC)/(b+tempC)) dampfDruck = rlHum / 100.0 * saettDampfDruck
v = math.log10(dampfDruck/6.1078)
dewpC = b*v/(a-v)
return dewpC
# translate cm into inches
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
vdewpoint = vectorize(dewpoint)
convertDate = lambda x: datetime.datetime.utcfromtimestamp(x) data = np.genfromtxt('/home/pi/',
delimiter=';',
usecols=(1, 2, 3, 5, 6),
names=['temp', 'humidity', 'press', 'slp', 'time'],
converters={'6': convertDate},
dtype='float, float, float, float, int')
print data
plt.figure(figsize=cm2inch(29.7, 21))
host = host_subplot(111, axes_class=aa.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 70 # offset of detached axis
new_fixed_axis = _grid_helper().new_fixed_axis
par2.axis["right"] = _grid_helper().new_fixed_axis(loc="right", axes=par2,
offset=(offset, 0))
par1.axis["right"].toggle(all=True)
par2.axis["right"].toggle(all=True)
host.set_title("Weather Station")
host.set_xlabel("Time")
host.set_ylabel("Temperature & Dewpoint [" + u'\u00b0'+ "C]")
par1.set_ylabel("Sealevel Pressure [hPa]")
par2.set_ylabel("relative Humidity [%]")
host.set_ylim([-20, 40]) # temperature range -20C (40)
par1.set_ylim([980, 1040]) # slp range 980hPa ... 1040hPa
par2.set_ylim([0, 100]) # percent
p1, = host.plot(data['time'],

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。