首页 > 解决方案 > 以上午/下午格式绘制多天数据 24 小时,但不断收到不规则的 xticks

问题描述

我用于绘图的最终数据框

我有一个索引为 DateTime 和温度为值的数据框。想要绘制每周和每月的数据,x 轴为时间,y 轴为温度。通过每周数据,我的意思是在一个 24 小时 x 轴图表中绘制 7 天数据,以便我可以查看是否出现某种模式。

我的原始数据框如下所示:

Date                      Temperature
2017-04-05 11:18:00-04:00  32.716833
2017-04-05 11:19:00-04:00  32.635500
2017-04-05 11:20:00-04:00  32.547333
...                              ...
2017-07-20 20:37:00-04:00  35.219667
2017-07-20 20:38:00-04:00  35.240000
2017-07-20 20:39:00-04:00  35.233000

这是我的代码。我正在尝试绘制温度,移动平均 7 天。1

#Weekly with matplotlib sorting dates in correct order
import matplotlib.pyplot as plt
from datetime import time
import matplotlib.dates as mdates
import seaborn as sns
import numpy as np
sns.set(style="darkgrid")
i = 0
fig, ax = plt.subplots(figsize=(18,8))#figsize=(15,15)
markers=['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']
i=0   # variable using for counter if i==7 (weekly)
#made a list of unique dates for loop  
for date in dates:
    # selecting dataframe for specific date
    df = df_sub[df_sub.date == date]
    plt.plot(df['NewTime'],df['TEMP'],markers[i],label=date)   
    i=i+1   
    if i % 1==0:
        i = 0
        print(date)
        plt.plot(df['NewTime'],df['fifteenminavg'], label='Mean', linestyle='--',c='darkgrey')
#         plt.xticks( rotation=25 )
#         ax=plt.gca()
        ax.set_xlim(["00:00:00", "23:59:59"])
        plt.title("Skin Temperature (Week="+str(date)+")",fontsize=20)
#         ax.set_xticks(np.linspace(0, 2*np.pi, 24, endpoint=True))
#         ticks = ['12 AM', '1 AM', '2 AM', '3 AM', '4 AM', '5 AM', '6 AM', '7 AM','8 AM','9 AM','10 AM','11 AM','12 PM', '1 PM', '2 PM', '3 PM', '4 PM',  '5 PM', '6 PM', '7 PM', '8 PM', '9 PM', '10 PM', '11 PM' ]
#         ax.set_xticklabels(tickstime)
#         ax=plt.gca()
#         hours = mdates.HourLocator(interval = 1)
#         h_fmt = mdates.DateFormatter('%H:%M:%S')
#         ax.xaxis.set_major_locator(hours)
#         ax.xaxis.set_major_formatter(h_fmt) 
        ax.set_ylabel('Temperature (°C)')
        ax.set_xlabel('Time')
        fig.autofmt_xdate()
        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        fig.tight_layout()
        plt.show()  
        fig, ax = plt.subplots(figsize=(18,8))#figsize=(15,15)

这是我的输出图.. 你可以看到 x-ticks 没有固定的间隔。

我希望他们像上午 12 点、上午 6 点、下午 12 点、下午 6 点、上午 12 点

带有 x 轴时间问题的图

标签: pythondatetimematplotlib

解决方案


推荐阅读