Matplotlib: How to create a color gradient for line plots based on a secondary variable?
I've looked through the documentation and I'm still confused about I'm prototyping a solution and I'm trying to create a line plot using Matplotlib where the color of the lines changes based on a secondary variable..... I have a dataset with two variables: `x` for the x-axis and `y` for the y-axis, but I'd like the color of the line segments to reflect a third variable, `z`. My goal is to visualize how `z` changes along the line defined by `x` and `y`. I've tried using `plt.plot()` along with a colormap, but it seems like the entire line takes on a single color instead of a gradient. Hereβs the code I've written so far: ```python import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection # Sample data x = np.linspace(0, 10, 100) y = np.sin(x) z = np.cos(x) # Secondary variable for color # Create segments and normalize z for color mapping points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # Normalize z for color mapping norm = plt.Normalize(z.min(), z.max()) colors = plt.cm.viridis(norm(z)) # Create the line collection lc = LineCollection(segments, cmap='viridis', norm=norm) lc.set_array(z) lc.set_linewidth(2) # Plotting fig, ax = plt.subplots() ax.add_collection(lc) ax.autoscale_view() ax.set_xlim(x.min(), x.max()) ax.set_ylim(y.min(), y.max()) plt.colorbar(lc, ax=ax, label='Cosine Values (z)') plt.title('Line Plot with Color Gradient') plt.show() ``` Although I'm able to see a color gradient in the colorbar, the actual line plot is still just one color. I'm unsure if Iβm correctly applying the `LineCollection`. Can anyone point me in the right direction? Is there a step I might have missed or a better approach to visualize this? Any help would be appreciated. My development environment is macOS. The project is a microservice built with Python. Could this be a known issue? What am I doing wrong?