- 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
Changing the formatting of a datetime axis in Matplotlib
To change the formatting of a datetime axis in matplotlib, we can take the following steps−
- Create a dataframe df using pandas DataFrame with time and speed as keys
- Create a figure and a set of subplots using subplots() method.
- Plot the dataframe using plot method, with df's (Step 1) time and speed.
- To adjust the tick labels, we can rotate tick_params by 45 degrees
- To edit the date formatting from %d-%m-%d to %d:%m%d, we can use set_major_formatter() method. Set the formatter of the major ticker.
- To display the figure, use show() method.
Example
import numpy as np import pandas as pd from matplotlib import pyplot as plt, dates plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(dict(time=list(pd.date_range("2021-01-01 12:00:00", periods=10)), speed=np.linspace(1, 10, 10))) fig, ax = plt.subplots() ax.plot(df.time, df.speed) plt.tick_params(rotation=45) ax.xaxis.set_major_formatter(dates.DateFormatter('%y:%m:%d')) plt.show()
Output
Advertisements