- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
How to show date and time on the X-axis in Matplotlib?
To show date and time on the X-axis in Matplotlib, we can take the following steps −
- Set the figure size and adjust the padding between and around the subplots.
- Create a list of dates and y values.
- Get the current axis.
- Set the major date formatter and locator.
- Plot x and y values using plot() method.
- To display the figure, use show() method.
Example
from datetime import datetime as dt from matplotlib import pyplot as plt, dates as mdates plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True dates = ["01/02/2020", "01/03/2020", "01/04/2020"] x_values = [dt.strptime(d, "%m/%d/%Y").date() for d in dates] y_values = [1, 2, 3] ax = plt.gca() formatter = mdates.DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(formatter) locator = mdates.DayLocator() ax.xaxis.set_major_locator(locator) plt.plot(x_values, y_values) plt.show()
Output
Advertisements