Tuesday, August 18, 2020

Plotting Time series using Python,Matplotlib and Seaborn

 # -*- coding: utf-8 -*-
"""Average_Plot_Assignment.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1je2kMjqPUPUzawk2IernYMR5lkwZgny1
"""

!pip install odfpy

import numpy as np
import datetime
from google.colab import files
import pandas as pd
df=pd.read_excel("/content/sample_data/arable__NIST_A_B_C_C003747_daily_20200818.ods", engine="odf")
#df.drop([df.index[0]],inplace=True)
 
#df = df.astype({"NIST A": np.float64, "NIST B": np.float64,"NIST C":np.float64},errors='coerce')
cols = ['NIST A', 'NIST B', 'NIST C']
df[cols] = df[cols].apply(pd.to_numeric,errors='coerce',axis=1)

df.fillna(0, inplace=True)

df[['Timestamp']] = df[['Timestamp']].apply(pd.to_datetime,errors='coerce',axis=1)
df.sort_values(by=['Timestamp'], inplace=True, ascending=True)
df['mean'] = df.mean(axis=1)
df= df.set_index('Timestamp')
df

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# Display figures inline in Jupyter notebook
import seaborn as sns
# Use seaborn style defaults and set the default figure size
sns.set(rc={'figure.figsize':(15, 4)})

fig, ax = plt.subplots()
ax.plot(df['mean'], marker='o', linestyle='-')
ax.set_ylabel('Mean')
ax.set_xlabel('Timestamp')
ax.set_title('Mean Vs Timestamp')
# Set x-axis major ticks to weekly interval, on Mondays
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MONDAY))
# Format x-tick labels as 3-letter month name and day number
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'));

# Specify the data columns we want to include (i.e. exclude Year, Month, Weekday Name)
data_columns = ['mean']
# Resample to weekly frequency, aggregating with mean
df_weekly_mean = df[data_columns].resample('W').mean()

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# Display figures inline in Jupyter notebook
import seaborn as sns
# Use seaborn style defaults and set the default figure size
sns.set(rc={'figure.figsize':(15, 4)})

# Start and end of the date range to extract
start, end = df.index.min(), df.index.max()
# Plot daily and weekly resampled time series together
fig, ax = plt.subplots()
ax.plot(df.loc[start:end, 'mean'],marker='.', linestyle='-', linewidth=1.0, label='Daily Mean')
ax.plot(df_weekly_mean.loc[start:end, 'mean'],marker='o', markersize=8, linestyle='-', label='Weekly Mean Resample')
ax.set_ylabel('Mean')
ax.legend();
fig.savefig("Fid.jpg",dpi=500,format='jpg', bbox_inches='tight')
files.download("Fid.jpg")

 

 

No comments:

Post a Comment