以不规则的间隔绘制日期时间x轴

时间:2019-07-17 11:58:09

标签: matplotlib

我想为自定义日期范围绘制数据。所以我的数据集就像每天早上8点到下午5点。我需要绘制5天的时间范围。我该怎么做,这样我就不会超出上面提到的其他时间范围。我尝试使用x定位器进行绘图,但是它显示了整个时间范围内的数据。

尝试设置x定位器不起作用

1 个答案:

答案 0 :(得分:0)

import datetime
from matplotlib import dates as mdates
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates
x= pd.date_range(start=datetime.datetime( 2019, 7, 8, 8, 0,0 ), freq='10min',end=datetime.datetime ( 2019, 7, 12, 17, 0 ,0))
start = datetime.time(8, 0, 0)
end = datetime.time(17, 0, 0)

def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end   

t= [i.to_datetime() for i in x if time_in_range(start,end,i.to_datetime().time())]



df=pd.DataFrame({'d':d,'t':t})
df=df.set_index('t')
fig,axes = plt.subplots()
axes.xaxis_date()
axes.bar(mdates.date2num(list(df.index)),df['d'],align='center',width=0.006,color='pink')
fig.autofmt_xdate()
xformatter = mdates.DateFormatter('%d/%m/%y:%H:%M')
xlocator = mdates.HourLocator(byhour=range(8,17,2))
axes.xaxis.set_major_locator(xlocator)
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
plt.show()
相关问题