Date Demo Convert

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Matplotlib is a data visualization library widely used in Python. It is capable of creating various types of graphs and charts such as line charts, bar charts, scatter plots, and more. In this tutorial, we will guide you through the process of creating a date demo convert graph using Matplotlib.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48651{{"`Date Demo Convert`"}} matplotlib/figures_axes -.-> lab-48651{{"`Date Demo Convert`"}} matplotlib/line_plots -.-> lab-48651{{"`Date Demo Convert`"}} python/lists -.-> lab-48651{{"`Date Demo Convert`"}} python/tuples -.-> lab-48651{{"`Date Demo Convert`"}} python/importing_modules -.-> lab-48651{{"`Date Demo Convert`"}} python/using_packages -.-> lab-48651{{"`Date Demo Convert`"}} python/standard_libraries -.-> lab-48651{{"`Date Demo Convert`"}} python/date_time -.-> lab-48651{{"`Date Demo Convert`"}} python/numerical_computing -.-> lab-48651{{"`Date Demo Convert`"}} python/data_visualization -.-> lab-48651{{"`Date Demo Convert`"}} python/build_in_functions -.-> lab-48651{{"`Date Demo Convert`"}} end

Import the necessary libraries

Before we can start creating the graph, we need to import the required libraries, which are Matplotlib, NumPy, and datetime. Copy and paste the following code:

import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.dates import DateFormatter, DayLocator, HourLocator, drange

Define the dates and delta

Next, we will define the dates and delta values using the datetime library. The date range will be from March 2, 2000, to March 6, 2000, with a 6-hour interval. Copy and paste the following code:

date1 = datetime.datetime(2000, 3, 2)
date2 = datetime.datetime(2000, 3, 6)
delta = datetime.timedelta(hours=6)
dates = drange(date1, date2, delta)

Define the y values

After defining the date range, we will create the y values using NumPy's arange function. The y values will have the same length as the number of dates. Copy and paste the following code:

y = np.arange(len(dates))

Create the graph

Now, we can create the graph using the dates and y values. We will first create a figure and axis object using the subplots function. Then, we will plot the graph using the plot function. Copy and paste the following code:

fig, ax = plt.subplots()
ax.plot(dates, y**2, 'o')

Set the x-axis and format the dates

To make the graph more readable, we will set the x-axis limits to the first and last dates in the range. We will also set the major and minor locators to DayLocator and HourLocator, respectively. Finally, we will format the dates using the DateFormatter function. Copy and paste the following code:

ax.set_xlim(dates[0], dates[-1])
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')

Rotate the x-axis labels

By default, the x-axis labels are in a horizontal orientation. We can rotate the labels to a diagonal orientation to make them more readable. Copy and paste the following code:

fig.autofmt_xdate()

Display the graph

Finally, we can display the graph using the show function. Copy and paste the following code:

plt.show()

Summary

In this tutorial, we have learned how to create a date demo convert graph using Matplotlib. We covered importing the necessary libraries, defining the dates and y values, creating the graph, formatting the x-axis, and displaying the graph. With this knowledge, you can start creating your own custom graphs and charts using Matplotlib.

Other Python Tutorials you may like