Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Plot numpy datetime64 with Matplotlib
To plot a time series in Python using matplotlib with numpy datetime64, we need to create datetime arrays and plot them against numerical values. This is commonly used for visualizing time-based data like stock prices, sensor readings, or any data that changes over time.
Basic Steps
Create x points using numpy datetime64 arrays
Create corresponding y points with numerical data
Plot the datetime x-axis against y values using plot() method
Display the figure using show() method
Example
Let's create a simple time series plot with hourly data for a single day ?
import matplotlib.pyplot as plt
import datetime
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create datetime array for 24 hours
x = np.array([datetime.datetime(2021, 1, 1, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x, y)
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Time Series Plot with Datetime64')
plt.show()
Using numpy.datetime64 Directly
You can also create datetime arrays using numpy's datetime64 type directly ?
import matplotlib.pyplot as plt
import numpy as np
# Create datetime64 array
start_date = np.datetime64('2021-01-01')
x = np.arange(start_date, start_date + np.timedelta64(30, 'D'), np.timedelta64(1, 'D'))
y = np.random.randn(30).cumsum()
plt.plot(x, y, marker='o')
plt.xlabel('Date')
plt.ylabel('Cumulative Value')
plt.title('30-Day Time Series')
plt.xticks(rotation=45)
plt.show()
Formatting Date Axis
For better readability, you can format the date axis using matplotlib's date formatting ?
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
# Create datetime64 array for one week
dates = np.arange('2021-01-01', '2021-01-08', dtype='datetime64[D]')
values = [23, 45, 56, 78, 32, 67, 89]
plt.figure(figsize=(10, 6))
plt.plot(dates, values, marker='s', linewidth=2)
# Format x-axis
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1))
plt.xticks(rotation=45)
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Weekly Data with Formatted Dates')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Conclusion
Matplotlib automatically handles numpy datetime64 objects for time series plotting. Use matplotlib.dates for advanced date formatting and np.datetime64 for creating date ranges efficiently.
