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
Selected Reading
How to plot multi-color line if X-axis is datetime index of Pandas?
To plot a multi-color line where the X-axis is a datetime index in Pandas, you need to use LineCollection from matplotlib with a colormap. This creates segments between consecutive points, each colored based on the x-value position.
Creating Sample Data
First, let's create a datetime-indexed Pandas Series with random walk data ?
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt, dates as mdates, collections as mcoll
# Create datetime range and random walk data
dates = pd.date_range("2021-01-01", "2021-06-01", freq="7D")
values = np.cumsum(np.random.normal(size=len(dates)))
series = pd.Series(values, index=dates)
print("Sample data:")
print(series.head())
Sample data: 2021-01-01 0.496714 2021-01-08 -0.861229 2021-01-15 -2.242685 2021-01-22 -1.790377 2021-01-29 -3.003467 Freq: 7D, dtype: float64
Creating Multi-Color Line Plot
Use LineCollection to create segments between consecutive points, colored by position ?
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt, dates as mdates, collections as mcoll
# Set up figure
plt.rcParams["figure.figsize"] = [10, 5]
plt.rcParams["figure.autolayout"] = True
# Create sample data
dates = pd.date_range("2021-01-01", "2021-06-01", freq="7D")
values = np.cumsum(np.random.normal(size=len(dates)))
series = pd.Series(values, index=dates)
# Create plot
fig, ax = plt.subplots()
# Convert datetime to matplotlib format
x_values = mdates.date2num(series.index.to_pydatetime())
# Create line segments for coloring
points = np.array([x_values, series.values]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# Create LineCollection with colormap
line_collection = mcoll.LineCollection(segments, cmap="viridis", linewidth=2)
line_collection.set_array(x_values)
# Add to plot and format
ax.add_collection(line_collection)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
ax.autoscale_view()
# Add labels and colorbar
plt.xlabel("Date")
plt.ylabel("Value")
plt.title("Multi-Color Line Plot with Datetime Index")
plt.colorbar(line_collection, label="Time Progression")
plt.xticks(rotation=45)
plt.show()
Alternative Approach Using Scatter Plot
For simpler cases, you can use a scatter plot with line connections ?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
dates = pd.date_range("2021-01-01", "2021-06-01", freq="7D")
values = np.cumsum(np.random.normal(size=len(dates)))
series = pd.Series(values, index=dates)
# Create plot with color mapping
fig, ax = plt.subplots(figsize=(10, 5))
# Plot line in background
ax.plot(series.index, series.values, color='lightgray', linewidth=1, alpha=0.7)
# Add colored scatter points
colors = plt.cm.plasma(np.linspace(0, 1, len(series)))
ax.scatter(series.index, series.values, c=colors, s=30, zorder=5)
# Format plot
ax.set_xlabel("Date")
ax.set_ylabel("Value")
ax.set_title("Multi-Color Points with Datetime Index")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Key Components
| Component | Purpose | Usage |
|---|---|---|
LineCollection |
Creates colored line segments | Multi-color continuous lines |
date2num() |
Converts datetime to numeric | Required for LineCollection |
DateFormatter |
Formats date labels | Readable x-axis labels |
set_array() |
Maps values to colors | Determines color intensity |
Conclusion
Use LineCollection with date2num() to create multi-color lines with datetime indices. The colormap maps time progression to colors, creating visually appealing time series plots.
Advertisements
