Skip to content

BUG: Slower DataFrame.plot with DatetimeIndex #61398

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
3 tasks done
Abdelgha-4 opened this issue May 6, 2025 · 7 comments
Open
3 tasks done

BUG: Slower DataFrame.plot with DatetimeIndex #61398

Abdelgha-4 opened this issue May 6, 2025 · 7 comments
Assignees
Labels
Datetime Datetime data dtype Performance Memory or execution speed performance Visualization plotting

Comments

@Abdelgha-4
Copy link

Abdelgha-4 commented May 6, 2025

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

# Imports & data generation
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

num_rows = 500
num_cols = 2000

index = pd.date_range(start="2020-01-01", periods=num_rows, freq="D")
test_df = pd.DataFrame(np.random.randn(num_rows, num_cols).cumsum(axis=0), index=index)


# Very Slow plot (1m 11.6s)
test_df.plot(legend=False, figsize=(12, 8))
plt.show()


# Much faster Plot using this workaround: (6.1s)

# 1. Plot a single column with dates to copy the right ticks
ax1 = test_df.iloc[:, 0].plot(figsize=(12, 6), legend=False)
xticks = ax1.get_xticks()
xticklabels = [label.get_text() for label in ax1.get_xticklabels()]
plt.close(ax1.figure)

# 2. Faster plot with no date index
ax2 = test_df.reset_index(drop=True).plot(legend=False, figsize=(12, 8))
# 3. Inject the date X axis info
num_ticks = len(xticks)
new_xticks = np.linspace(0, num_rows - 1, num_ticks)
ax2.set_xlim(0, num_rows - 1)
ax2.set_xticks(new_xticks)
ax2.set_xticklabels(xticklabels)
plt.show()

Issue Description

Plotting a large DataFrame with a DatetimeIndex and many rows and columns results in extremely slow rendering times. This issue can be surprisingly mitigated by first plotting a single column to generate the correct ticks and labels, then resetting the index and copying the ticks to plot the full DataFrame, gaining +11x speed improvement. This may suggests that a similar logic may be applied (if found consistent) to improve speed when applied.

Expected Behavior

No big difference in ploting time depending on the index type, especially if avoidable with the trick above.

Installed Versions

INSTALLED VERSIONS

commit : d9cdd2e
python : 3.12.4.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19045
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : fr_FR.cp1252

pandas : 2.2.2
numpy : 2.0.1
pytz : 2024.1
dateutil : 2.9.0.post0
setuptools : 75.3.0
pip : 25.0.1
Cython : None
pytest : 8.3.3
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 5.3.0
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.4
IPython : 8.26.0
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.12.3
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.9.2
numba : None
numexpr : 2.10.1
odfpy : None
openpyxl : 3.1.5
pandas_gbq : None
pyarrow : 17.0.0
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.14.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2024.1
qtpy : None
pyqt5 : None

@Abdelgha-4 Abdelgha-4 added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels May 6, 2025
@rhshadrach
Copy link
Member

Thanks for the report, confirmed on main. Further investigations and PRs to fix are welcome!

@rhshadrach rhshadrach added Visualization plotting Performance Memory or execution speed performance Datetime Datetime data dtype and removed Bug Needs Triage Issue that has not been reviewed by a pandas team member labels May 7, 2025
@thehalvo
Copy link

thehalvo commented May 9, 2025

take

@Abdelgha-4
Copy link
Author

Abdelgha-4 commented May 25, 2025

For anyone interested, I've found an even faster way to produce the same plot:

# Additional import
from matplotlib.collections import LineCollection

# 1. Same as above, plot a single column to copy the ticks
ax1 = test_df.iloc[:, 0].plot(figsize=(12, 6), legend=False)
xticks = ax1.get_xticks()
xticklabels = [label.get_text() for label in ax1.get_xticklabels()]
plt.close(ax1.figure)

# 2. This time using LineCollection
x = np.arange(len(test_df.index))
lines = [np.column_stack([x, test_df[col].values]) for col in test_df.columns]
default_colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
color_cycle = list(itertools.islice(itertools.cycle(default_colors), len(lines)))

line_collection = LineCollection(lines, colors=color_cycle)
fig, ax2 = plt.subplots(figsize=(10, 5))
ax2.add_collection(line_collection)
ax2.set_xlim(0, num_rows - 1)
ax2.margins(y=0.05)

# Injecting ticks, same as above
ax2.set_xticks(np.linspace(0, num_rows - 1, len(xticks)))
ax2.set_xticklabels(xticklabels)

plt.tight_layout()
plt.show()

This is 2.5x faster than my proposed workaround and 27x faster than DataFrame.plot.

@rhshadrach Please let me know if this is worth being a separate issue, or maybe out of scope.

@rhshadrach
Copy link
Member

Thanks for the work here @Abdelgha-4 - at a glance that looks good, but it'd be more informative to see what this would look like in the pandas code itself. Would you be willing to put up a PR?

@Abdelgha-4
Copy link
Author

Unfortunately I won't be able to work on a PR for the moment, but I've created a separate issue regarding this here: #61532, so that it's tracked and can be picked up by interested contributors.

@rhshadrach
Copy link
Member

rhshadrach commented Jun 2, 2025

@Abdelgha-4 - can you help me understand why we need a 2nd issue for this?

@Abdelgha-4
Copy link
Author

@rhshadrach IMO each issue adresses a different type of performance bottleneck:

  • The inefficiency in plotting DatetimeIndex, fully solvable using existing pandas functionality alone. So the focus there is on optimizing how pandas handles datetime axes internally.

  • New proposed structural change: using LineCollection instead of many Line2D objects. This involves integrating a Matplotlib feature that pandas plotting doesn't currently use, and could unlock consistent speedups for all large DataFrames — even when the index type isn't the bottleneck.

I judged that you can work on either of them without having to know about the other one, hence the separation. You can ofc disagree with the rationale here, in which case please feel free to close it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Datetime Datetime data dtype Performance Memory or execution speed performance Visualization plotting
Projects
None yet
Development

No branches or pull requests

3 participants