Certainly! Below is a Python function named anomaly_highlight that generates a line plot highlighting the occurrence of an anomaly in time-series data. This function uses pandas for data handling and matplotlib for plotting. It allows you to specify which columns to visualize and ensures that the anomaly point is centered with 24 hours of data surrounding it.
Function Overview
-
Parameters:
data (pd.DataFrame): Time-series data with a datetime index.
anomaly_time (pd.Timestamp or str): The timestamp where the anomaly occurs.
columns (list, optional): List of column names to visualize. Defaults to the first three columns if not provided.
window_hours (int, optional): Number of hours before and after the anomaly to display. Defaults to 24 hours.
-
Functionality:
- Validation & Setup:
- Ensures the DataFrame is sorted by its datetime index.
- Validates and parses the
anomaly_time.
- Data Slicing:
- Extracts a window of data centered around the
anomaly_time (default ±24 hours).
- Plotting:
- Plots the specified columns.
- Highlights the anomaly point with distinct markers and a vertical dashed line.
- Customization:
- Allows overriding default columns and window size through function parameters.
Prerequisites
Make sure you have the necessary libraries installed. You can install them using pip if you haven't already:
pip install pandas matplotlib
Implementation
import pandas as pd
import matplotlib.pyplot as plt
def anomaly_highlight(data, anomaly_time, columns=None, window_hours=24):
"""
Generates a line plot highlighting the occurrence of an anomaly.
Parameters:
- data (pd.DataFrame): Time-series data with a datetime index.
- anomaly_time (pd.Timestamp or str): The timestamp where the anomaly occurs.
- columns (list of str, optional): Columns to visualize. Defaults to the first three columns.
- window_hours (int, optional): Number of hours before and after the anomaly to display. Defaults to 24.
Returns:
- None: Displays a matplotlib plot.
"""
# Ensure the index is datetime
if not pd.api.types.is_datetime64_any_dtype(data.index):
raise ValueError("The DataFrame index must be a datetime type.")
# Parse anomaly_time if it's a string
if isinstance(anomaly_time, str):
anomaly_time = pd.to_datetime(anomaly_time)
elif not isinstance(anomaly_time, pd.Timestamp):
raise TypeError("anomaly_time must be a pandas Timestamp or a string representing a datetime.")
# Set default columns if not provided
if columns is None:
columns = data.columns[:3].tolist()
else:
# Validate columns
for col in columns:
if col not in data.columns:
raise ValueError(f"Column '{col}' not found in the DataFrame.")
# Ensure data is sorted
data = data.sort_index()
# Define the time window
start_time = anomaly_time - pd.Timedelta(hours=window_hours)
end_time = anomaly_time + pd.Timedelta(hours=window_hours)
# Slice the data within the window
plot_data = data.loc[start_time:end_time]
# Check if there's data to plot
if plot_data.empty:
raise ValueError("No data available in the specified window around the anomaly_time.")
# Create the plot
plt.figure(figsize=(14, 7))
for col in columns:
plt.plot(plot_data.index, plot_data[col], label=col)
# Highlight the anomaly point
if anomaly_time in plot_data.index:
anomaly_values = data.loc[anomaly_time, columns]
else:
# Find the closest timestamp if exact anomaly_time is not in the index
closest_idx = data.index.get_indexer([anomaly_time], method='nearest')[0]
anomaly_time = data.index[closest_idx]
anomaly_values = data.iloc[closest_idx][columns]
for col in columns:
plt.plot(anomaly_time, anomaly_values[col], 'o', markersize=10, label=f'Anomaly ({col})')
# Add a vertical line at the anomaly_time
plt.axvline(x=anomaly_time, color='red', linestyle='--', linewidth=2, label='Anomaly Timestamp')
# Enhance the plot
plt.title('Anomaly Highlight in Time-Series Data', fontsize=16)
plt.xlabel('Time', fontsize=14)
plt.ylabel('Value', fontsize=14)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Example Usage
Suppose you have a DataFrame df with a datetime index and multiple columns representing different metrics. Here's how you can use the anomaly_highlight function:
# Sample DataFrame creation for demonstration
import numpy as np
# Create a date range
date_rng = pd.date_range(start='2023-01-01', end='2023-01-03', freq='H')
# Create a DataFrame with random data
np.random.seed(42)
df = pd.DataFrame({
'temperature': np.random.normal(loc=20, scale=5, size=len(date_rng)),
'humidity': np.random.normal(loc=50, scale=10, size=len(date_rng)),
'pressure': np.random.normal(loc=1013, scale=15, size=len(date_rng))
}, index=date_rng)
# Introduce an anomaly
anomaly_point = pd.Timestamp('2023-01-02 12:00:00')
df.loc[anomaly_point] = [100, 200, 1200] # Extreme values as anomaly
# Plotting the anomaly
anomaly_highlight(
data=df,
anomaly_time='2023-01-02 12:00:00',
columns=['temperature', 'humidity', 'pressure'],
window_hours=24
)
Explanation of the Example
-
Data Preparation:
- A sample DataFrame
df is created with hourly data for two days.
- An anomaly is artificially introduced at
'2023-01-02 12:00:00' by setting extreme values.
-
Function Call:
anomaly_highlight is called with the DataFrame df, specifying the anomaly time.
- It visualizes the
'temperature', 'humidity', and 'pressure' columns.
- The plot displays data from 24 hours before to 24 hours after the anomaly, centering the anomaly in the plot.
-
Result:
- The generated plot will show the three specified metrics over the 48-hour window.
- The anomaly point is marked with distinct markers and a vertical dashed red line to easily identify its position.
Customization
-
Changing Columns:
If you want to visualize different columns, simply pass a list of column names to the columns parameter.
anomaly_highlight(
data=df,
anomaly_time='2023-01-02 12:00:00',
columns=['temperature', 'pressure'], # Only temperature and pressure
window_hours=24
)
-
Adjusting the Time Window:
To visualize a different time window around the anomaly, modify the window_hours parameter.
anomaly_highlight(
data=df,
anomaly_time='2023-01-02 12:00:00',
columns=['temperature', 'humidity', 'pressure'],
window_hours=12 # 12 hours before and after
)
Notes
-
Datetime Index: The function assumes that the DataFrame has a datetime index. If your datetime information is in a column, set it as the index before using the function:
df.set_index('your_datetime_column', inplace=True)
-
Handling Missing Data: If there are missing timestamps within the window, the plot will still display based on available data. Ensure your time-series data is properly indexed and cleaned for accurate visualization.
-
Extensibility: You can further enhance the function by adding parameters for plot styling, saving the plot to a file, or handling multiple anomalies.
I hope this helps you effectively visualize and highlight anomalies in your time-series data!