matplotlib-label-lines icon indicating copy to clipboard operation
matplotlib-label-lines copied to clipboard

ValueError with `labellines` when plotting rolling mean with NaNs

Open Vasco-Da-Gama-png opened this issue 8 months ago • 0 comments

Bug Report: ValueError with labellines when plotting rolling mean with NaNs

Description

When using the labellines package to label lines in a plot that includes a rolling mean with NaN values, a ValueError is raised with the message "x label location is outside data range". This issue occurs even though the commit 0a517f7 was supposed to handle NaN values.

Minimal Example

The following minimal example demonstrates the issue. It creates a DataFrame with random values and some NaN values, calculates the rolling mean, and then attempts to label the lines using labellines.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from labellines import labelLines

# Create a DataFrame with random values and NaNs
np.random.seed(0)
time = pd.date_range(start="2025-01-01", periods=100, freq="T")
data = np.random.randn(100).cumsum()
data[20:30] = np.nan  # Add some NaN values

df = pd.DataFrame({"Time": time, "Value": data})

# Calculate the rolling mean
roll_mean = df["Value"].rolling(window=10).mean()

# Plot the data and the rolling mean
fig, ax = plt.subplots()
ax.plot(df["Time"], df["Value"], label="Original Data", alpha=0.5)
ax.plot(df["Time"], roll_mean, label="Rolling Mean", linewidth=2)

# Use labellines to label the lines
try:
    labelLines(ax.get_lines(), align=False)
except ValueError as e:
    print(f"Error: {e}")

# Show the plot
plt.show()

Expected Behavior

The labellines function should label the lines without raising a ValueError, even when the data contains NaN values.

Actual Behavior

A ValueError is raised with the message "x label location is outside data range".

Environment

matplotlib version: [3.10.1] labellines version: [Github Main branch] Python version: [3.11.4] Operating System: [Debian buster]

Additional Information

The issue seems to be related to the handling of NaN values in the data. The commit 0a517f7 was supposed to address this, but the problem persists when plotting rolling means.

Vasco-Da-Gama-png avatar Mar 14 '25 10:03 Vasco-Da-Gama-png