- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating a graph with date and time in axis labels with Matplotlib
To create a graph with date and time in axis labels, we can take the following steps−
- Create a figure and add a set of subplots.
- Create x and y data points using numpy.
- Set date formatter for X-axis.
- Plot x and y using plot() method.
- Set the ticks of X-axis.
- Set the date-time tick labels for X-axis, with some rotation.
- Make the plot tight layout using plt.tight_layout() method.
- To display the figure, use show() method.
Example
from matplotlib import pyplot as plt, dates import datetime import numpy as np plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig, ax = plt.subplots() x = np.array([datetime.datetime(2021, 1, 1, i, 0) for i in range(5)]) y = np.random.randint(5, size=x.shape) ax.xaxis.set_major_formatter(dates.DateFormatter('%m-%d %H:%M')) plt.plot(x, y) ax.set_xticks(x) ax.set_xticklabels(x, rotation=30, fontdict={'horizontalalignment': 'center'}) plt.show()
Output
- Related Articles
- How to show date and time on the X-axis in Matplotlib?
- How to hide axes but keep axis-labels in 3D Plot with Matplotlib?
- How to change the separation between tick labels and axis labels in Matplotlib?
- Creating a Heatmap in matplotlib with pcolor
- Hide axis values but keep axis tick labels in matplotlib
- Drawing a network graph with networkX and Matplotlib
- Barchart with vertical labels in Python/Matplotlib
- Tweaking axis labels and names orientation for 3D plots in Matplotlib
- Show tick labels when sharing an axis in Matplotlib
- Increasing the space for X-axis labels in Matplotlib
- Create ggplot2 graph with darker axes labels, lines and titles in R
- How to plot a Bar Chart with multiple labels in Matplotlib?
- Create ggplot2 graph with reversed Y-axis and X-axis on top in R.
- Creating curved edges with NetworkX in Python3 (Matplotlib)
- Change values on matplotlib imshow() graph axis

Advertisements