Исправление формата даты и времени в xticks при построении в python - PullRequest
0 голосов
/ 18 октября 2018

Я пытался закодировать этот небольшой сценарий данных, но до сих пор мне было очень трудно добиться правильной обработки моей отметки даты / времени.Я достиг, я не знаю, правильно ли, чтобы показать и отредактировать мои xticks для моих дат, но не в цикле for, отображающем ежедневные данные месяца каждый час с интервалами в 10 минут.Я хочу, чтобы только основные тики в часах и незначительные тики каждые 10 минут.Любые предложения, которые помогут улучшить мой код :)?Я благодарю вас всех заранее!

import os
import pandas as pd
import matplotlib.pyplot as plt
import glob
import time
import matplotlib.dates as mdates
import numpy as np


path='Data1/'

##getting only .csv data###
filenames=glob.glob(path+"/*.csv")

###appending and reading all .csv files in a list including dataframes####
dfs=[]
for files in filenames:
    df1=pd.read_csv(files, header=0, usecols=range(2), nrows=5, index_col=None, parse_dates=['Date/time'])
    dfs.append(df1)

###creating big dataframe with all data###
dffinal=pd.concat(dfs, axis=0).reset_index(drop=True)
#print (dffinal)

##### splitting Date/time into two new columns#############
dffinal['Dates']=dffinal['Date/time'].dt.date
#dffinal['Dates']=dffinal['Date/time'].dt.strftime('%Y-%m-%d') ###output=object
dffinal['Time']=dffinal['Date/time'].dt.strftime('%H:%M:%S')###output=object
#dffinal['Time']=pd.to_timedelta(dffinal['Date/time'].dt.strftime('%H:%M:%S')) ###timedelta64[ns]
#dffinal['Times64']=pd.to_datetime(dffinal['Time'], format='%H:%M:%S') ##output=object
#dffinal['Times64']=pd.to_timedelta(dffinal['Date/time'], unit='s') ##output=timedelta64[ns]
#dffinal['Dates']=pd.to_datetime(dffinal['Date/time']).dt.date ###output=object
#dffinal['Time']=pd.to_datetime(dffinal['Date/time']).dt.time #####output=object
print(dffinal.dtypes)
#dffinal=dffinal.drop('Date/time', axis=1) #### if needed, but useful later

####eliminating merged Date/time column
#dffinal=dffinal.drop('Date/time', axis=1)
##print(dffinal)
#
#####rearanging column order. First all columns into a list. Then move Date an Time columns upfront
cols=dffinal.columns.tolist()
#print(cols)
#cols=cols[-1:]+cols[:-1]
#print(cols)
#dffinal=dffinal[cols]
dffinal=dffinal.rename(columns={'Top;wind_speed;Avg':'WS_Top[m/s]'})
#print(dffinal.dtypes)
########creating time column to plot####################
#dftimelist=dffinal.loc[0:143,['Time']]
#timelist=dftimelist['Time'].tolist()
#
#
####computing mean from big dataframe dffinal and grouping it###
dfmean=dffinal.groupby(['Dates']).mean()
dfmean.reset_index(inplace=True)
dfmean.columns=['Dates', 'Mean_WS[m/s]']
#
#print(dfmean)

#####when creating a scatter plot, only lists are able to be given as an input. Therefroe, the dates must be daken out from the dataframe and inserted in a new list###
#datelist=dfmean['Dates'].tolist()
#wslist=dfmean['Mean_WS[m/s]'].tolist()
########### creating mean wind spead of the month dataframe########
ws_mean_jan = dfmean['Mean_WS[m/s]'].mean()
wsmean_df_jan=pd.DataFrame(ws_mean_jan, dfmean['Dates'], columns=['WSmean']) ###index=dfmean['Dates']
wsmean_df_jan.reset_index(inplace=True)
wsmean_df_jan.columns=['Dates', 'Jan_WS[m/s]']
###############################################################################
#print(wsmean_df_jan)
####creating scatter and line plots##########
fig, ax= plt.subplots(figsize=(15, 6))
####using ax.scatter the x=List(datelist) must be an array or a string. It cant be a datetime.date object!!!!!! Using strftime() will not work when applying DayLocater()
#ax.scatter(datelist, dfmean['Mean_WS[m/s]'], color='b')
ax.plot(dfmean['Dates'], dfmean['Mean_WS[m/s]'], color='teal', marker='o')
ax.plot(dfmean['Dates'], wsmean_df_jan['Jan_WS[m/s]'], color='coral')

ax=plt.gca()
days=mdates.DayLocator()
dformat=mdates.DateFormatter('%d-%m')
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(dformat)
ax.set_xlim(dfmean['Dates'].iloc[0], dfmean['Dates'].iloc[-1]) ### if using a list containing dates :(datelist[0], datelist[-1])
ax.set_ylim(0,6)
ax.legend()
ax.grid(True)
fig.autofmt_xdate()###will format dates to fit properly and nice####
#plt.legend()
############creating groups of dataframes with groupby with DAte as grouping key########
fig2, ax1= plt.subplots(figsize=(15, 6))
#
#
for date, dfdates in dffinal.groupby(['Dates']):
    dfdates.set_index(['Date/time'], inplace=True)
#    dfdates=dfdates.reset_index(drop=True)
#    
#ax1.plot(datelist,dfdates['Top;wind_speed;Avg'])
    dfdates.plot(x=dfdates.index, y='WS_Top[m/s]', sharex=True, ax=ax1, legend=False)

#    print(dfdates)
######print(list(dfdates))
#hourly_ticks = 1 * 60 * 60 * np.arange(24)
#plt.xticks(hourly_ticks)
ax1=plt.gca()
hours=mdates.HourLocator(interval=4)
tformat=mdates.DateFormatter('%H:%M')
#ax1.setxticks(dfdates.index)
ax1.xaxis.set_major_locator(hours)
ax1.xaxis.set_major_formatter(tformat)
#ax1.set_xlim(timelist[0], timelist[-1])
ax1.set_ylim(0,8)    
##
##
#plt.show() 
...