Skip to content Skip to sidebar Skip to footer

Python Script to Plot Read Csv Timestamp

Plot Time Series data in Python using Matplotlib

In this tutorial we will learn to create a scatter plot of time series information in Python using matplotlib.pyplot.plot_date(). We will use Pandas Dataframe to excerpt the fourth dimension series data from a CSV file using pandas.read_csv().

The syntax and the parameters of matplotlib.pyplot.plot_date()

The syntax for plt.plot_date() is :-

matplotlib.pyplot.plot_date(10, y, fmt='o', tz=None, xdate=True, ydate=False, *, data=None, **kwargs)

and it returns a list of Line2D objects representing the plotted information.

The parameters of matplotlib.pyplot.plot_date() are shown in the table below:-

# Parameter Blazon Description
1 x,y assortment-similar The coordinates of the information points. If xdate or ydate is True, the respective values x or y are interpreted equally Matplotlib dates.
2 fmt str, optional The plot format cord. For details, come across the corresponding parameter in plot.
iii tz [ None | timezone string | tzinfo case] The fourth dimension zone to use in labeling dates. If None, defaults to rcParam timezone.
4 xdate bool, optional, default: True If True, the 10-axis will exist interpreted as Matplotlib dates.
5 ydate bool, optional, default: Imitation If True, the y-axis volition exist interpreted as Matplotlib dates.

Creating a scatter plot from time series information in Python Matplotlib

Beginning of all, we volition create a scatter plot of dates and values in Matplotlib using plt.plot_date(). We volition be using Python's built-in module chosen datetime(datetime, timedelta) for parsing the dates. And then, let us create a python file called 'plot_time_series.py' and make necessary imports.

We will be using seaborn fashion to create besprinkle plot of the time serial data. Finally, we will be passing dates and values to plt.plot_date() method and call plt.show() to plot.

          # plot_time_series.py  import matplotlib.pyplot every bit plt from datetime import datetime, timedelta plt.manner.utilize('seaborn')  dates = [     datetime(2019, 8, 21),     datetime(2019, viii, 22),     datetime(2019, 8, 23),     datetime(2019, eight, 24),     datetime(2019, 8, 25),     datetime(2019, 8, 26),     datetime(2019, 8, 27), ]  y = [0, ane, two, three, iv, 5, vi]  plt.plot_date(dates, y) plt.tight_layout() plt.show()                  

This will create a simple scatter plot for the fourth dimension serial data.

plot time series python_.png

Creating a line plot from time series information in Python Matplotlib

If we want to create a line plot instead of the scatter plot, we will have to gear up linestyle='solid' in plt.plot_date(). We can also change the markers.

          # plot_time_series.py  plt.plot_date(dates, y, linestyle ='solid')                  

Aligning engagement ticks labels in Matplotlib

Sometimes, we are working with a lot of dates and showing them horizontally won't be a good idea in that case. So, nosotros tin can as well change the alignment of the dates on x-axis of time serial plot by using autofmt_xdate() on plt.gcf().

          # plot_time_series.py  plt.gcf().autofmt_xdate                  

plot time series_python_.png

Formatting dates in Time Series plots in Matplotlib using Python

We volition be formatting the date in our time series plot by using dates from matplotlib. Nosotros will exist passing a python format cord , every bit we would have passed to strftime to format the date in our fourth dimension series plot.

So, I volition be using matplotlib.dates.DateFormatter to format the date in DD-MM-YYYY and and then pass it to set_major_formatter() method of matplotlib.pyplot.gca().

          # plot_time_series.py  date_format = mpl_dates.DateFormatter('%d-%chiliad-%Y') plt.gca().xaxis.set_major_formatter(date_format)                  

plot time_series_python_.png

Plotting time series data in Python from a CSV File

Currently, we were using hard-fed example data to plot the time serial. Now nosotros will be grabbing a existent csv file of bitcoin prices from here and and then create a time serial plot from that CSV file in Python using Matplotlib. So, now we have the time series information in CSV file called 'plot_time_series.csv'. Permit united states plot this time series data. We will exist using pandas' read_csv method to plot the time series information:-

          # plot_time_series.py  information = pd.read_csv('plot_time_series.csv') price_date = data['Engagement'] price_close = data['Close'] plt.plot_date(price_date, price_close, linestyle='solid')                  

plot_time_series_python_.png

Converting the dates to datetime format

One matter to note here is that the dates on x-axis are shown as strings and non the dates so DateFormatter won't piece of work on that. To brand them appointment objects, we will be using pandas.to_datetime.

          # plot_time_series.py  import matplotlib.pyplot equally plt from datetime import datetime, timedelta from matplotlib import dates as mpl_dates import pandas as pd plt.style.apply('seaborn')  data = pd.read_csv('plot_time_series.csv') data['Date'] = pd.to_datetime(data['Date']) data.sort_values('Date', inplace=True) price_date = data['Appointment'] price_close = data['Shut'] plt.plot_date(price_date, price_close, linestyle='solid') plt.gcf().autofmt_xdate() date_format = mpl_dates.DateFormatter('%d-%m-%Y') plt.gca().xaxis.set_major_formatter(date_format) plt.tight_layout() plt.title('Bitcoin Prices') plt.xlabel('Date') plt.ylabel('Closing') plt.show()                  

plot_time_series_python.png

So, in this tutorial we have learned to plot time series data in python from raw information as well as csv using pandas. Nosotros also learned how to change the scatter fourth dimension serial plot to line time series plot and much more.

Matplotlib Video Tutorial Series

We are glad to inform you that we are coming up with the Video Tutorial Serial of Matplotlib on Youtube. Check it out below.

Table of Contents of Matplotlib Tutorial in Python

Matplotlib Tutorial in Python | Affiliate i | Introduction

Matplotlib Tutorial in Python | Chapter two | Extracting Information from CSVs and plotting Bar Charts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4

Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5

Python Histograms | Matplotlib Tutorial in Python | Chapter half-dozen

Scatter Plotting in Python | Matplotlib Tutorial | Chapter seven

Plot Fourth dimension Series in Python | Matplotlib Tutorial | Chapter 8

Python Realtime Plotting | Matplotlib Tutorial | Affiliate ix

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10

Python Candlestick Nautical chart | Matplotlib Tutorial | Chapter 11

In the next tutorial we will exist learning to plot live data in existent-time. Stay tuned.

If you accept liked our tutorial, in that location are various ways to support us, the easiest is to share this mail service. You can also follow us on facebook, twitter and youtube.

In case of any query, you can leave the comment beneath.

If yous want to back up our piece of work. You tin do it using Patreon.

numbersspleace87.blogspot.com

Source: https://saralgyaan.com/posts/plot-time-series-in-python-matplotlib-tutorial-chapter-8/

Post a Comment for "Python Script to Plot Read Csv Timestamp"