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
How to plot a time series in Python?
To plot a time series in Python using matplotlib, we can take the following steps −
Create x and y points, using numpy.
Plot the created x and y points using the plot() method.
To display the figure, use the show() method.
Basic Time Series Plot
Here's a simple example that creates hourly data points for a full day ?
import matplotlib.pyplot as plt
import datetime
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create datetime points 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')
plt.show()
Using Pandas for Time Series
Pandas provides better support for time series data with built-in plotting capabilities ?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Create date range
dates = pd.date_range('2021-01-01', periods=30, freq='D')
values = np.random.randn(30).cumsum()
# Create DataFrame
df = pd.DataFrame({'value': values}, index=dates)
# Plot using pandas
df.plot(figsize=(10, 4))
plt.title('30-Day Time Series')
plt.ylabel('Cumulative Value')
plt.show()
Adding Formatting and Labels
For better visualization, add proper formatting, labels, and rotation for dates ?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Generate sample data
dates = pd.date_range('2021-01-01', periods=12, freq='M')
sales = np.random.randint(1000, 5000, size=12)
plt.figure(figsize=(10, 6))
plt.plot(dates, sales, marker='o', linestyle='-', linewidth=2)
plt.title('Monthly Sales Data', fontsize=16)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Sales ($)', fontsize=12)
plt.xticks(rotation=45)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Key Points
Use
datetimeobjects for the x-axis when dealing with time dataPandas
date_range()simplifies creating time sequencesAlways add proper labels and titles for clarity
Use
plt.xticks(rotation=45)to rotate date labels for better readability
Conclusion
Python's matplotlib and pandas make time series plotting straightforward. Use datetime objects for proper time axis formatting, and pandas for more complex time series operations with built-in plotting methods.
