Creating Time Series Plots with Matplotlib
Have you ever wondered how to create informative and visually appealing time series plots that showcase trends and patterns in data over time? Well, look no further! In this brief guide, we'll explore how to create time series plots using the Matplotlib library in Python.
Getting Started with Time Series Data
Time series data typically involves observations collected or recorded at different points in time. This could be anything from stock prices and weather measurements to sales figures and website traffic. Visualizing this data can help us identify trends, seasonal patterns, and anomalies.
Step 1: Import Libraries
Begin by bringing in the important tools:
Pandas for data manipulation
Matplotlib for visualization
DateTime for handling dates.
# Import Libraries
import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates
Step 2: Load Dataset
In this example, we're using a CSV file named "Timeseries Date for Matplotlib.csv". The pd. read_csv() function from the panda's library reads the data.
#Loading Dataset
df = pd.read_csv(r"/content/Timeseries Date for Matplotlib.csv")
df.head()
Step 3: Make Dates Easier to Work With
Now, make sure the dates are in a useful format. Change the type of data in the "Date" column from string to dates. Then, arrange the data in order based on the dates.
# Convert the date_column to datetime datatype
df['Date'] = pd.to_datetime(df['Date'])
#Sorting our Date
df.sort_values('Date', inplace=True)
Step 4: Create the Plot
Now, use the plt. plot() function to create the time series plot.
#Plotting the Time Series Data
plt.style.use('seaborn-v0_8')
price_date = df['Date']
btc_price_close = df['Open']
plt.plot_date(price_date, btc_price_close, linestyle='solid')
plt.tight_layout()
Step 5: Customizations
Rotating the Date Axis for a Better View: To improve how the dates look on the axis, rotate them using this code line.
#Customizations 1
#Rotating the date axis
plt.style.use('seaborn-v0_8')
price_date = df['Date']
btc_price_close = df['Open']
plt.plot_date(price_date, btc_price_close, linestyle='solid')
plt.tight_layout()
#Rotating the Date axis
plt.gcf().autofmt_xdate()
Change the Date format: Change the Date format from "2018-07-24" to "July 24, 2018" by using the DateFormatter class from the imported mpl_dates modules. Check HERE for other Dateformter codes.
#Change the Date format
plt.style.use('seaborn-v0_8')
price_date = df['Date']
btc_price_close = df['Open']
plt.plot_date(price_date, btc_price_close, linestyle='solid')
plt.tight_layout()
plt.gcf().autofmt_xdate()
#Using the DateFormatter Class
date_format = mpl_dates.DateFormatter('%b, %d %Y')
plt.gca().xaxis.set_major_formatter(date_format)
Add Your Touch: Now, personalize your plot. Give it a name, label the x-axis and y-axis, and make any other changes that you like.
#Other customizations
plt.style.use('seaborn-v0_8')
price_date = df['Date']
btc_price_close = df['Open']
plt.plot_date(price_date, btc_price_close, linestyle='solid')
plt.tight_layout()
plt.gcf().autofmt_xdate()
date_format = mpl_dates.DateFormatter('%b, %d %Y')
plt.gca().xaxis.set_major_formatter(date_format)
#Other customizaion
plt.xlabel('Date') #X-axis title
plt.ylabel('Open Price') #y-axis title
plt.title('BTC Open Prices') #Plot title
plt.show()
Creating time series plots with Matplotlib is a valuable skill for anyone dealing with time-dependent data. With a few lines of code, you can visualize trends, make informed decisions, and communicate your findings effectively. So, go ahead and explore the world of time series plots – you'll be amazed at the insights they can reveal!
Relevant Link: GitHub
Your support is invaluable
Did you like this article? Then please leave a share or even a comment, it would mean the world to me!
Don’t forget to subscribe to my YouTube account HERE, Where you will get a video explaining this article!