如何修改Matplotlib代码实现随Y值递增的黑红渐变线条?
How to Add a Black-to-Red Gradient to a Line in Matplotlib
Hey there! Great question—ordinary plt.plot() calls can't handle gradient colors directly, but we can fix this with Matplotlib's LineCollection tool. Here's exactly what you need to modify and the full working code:
Key Changes to Your Original Code
- Remove the single-color
plt.plot()line: Standard line plots don't support per-segment color gradients. We'll replace this with aLineCollectioninstead. - Add required imports: We need
LineCollectionfor segmented lines,matplotlib.cmfor color mapping, and make surenumpyis imported (your original code usesnpbut didn't include the import). - Create segmented line segments: Split your x/y data into tiny connected line segments, each of which we'll color based on its Y value.
- Map Y values to a black-to-red color scale: We'll create a custom colormap to go from black (low Y) to red (high Y).
- Add the collection to your axes and set proper limits: Unlike
plt.plot(),LineCollectiondoesn't auto-adjust axes limits, so we'll set those manually. - Add a colorbar: To show how Y values correspond to the gradient.
Full Modified Code
import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import cm # Original data xvals = np.arange(0, 1, 0.01) yvals = xvals # Create custom black-to-red colormap (exactly matches your requirement) black_red_cmap = cm.LinearSegmentedColormap.from_list( 'black_to_red', ['black', 'red'], N=256 ) # Split data into small line segments segments = np.array([xvals[:-1], yvals[:-1], xvals[1:], yvals[1:]]).T.reshape(-1, 2, 2) # Normalize Y values to fit the 0-1 range for color mapping norm = plt.Normalize(yvals.min(), yvals.max()) # Assign colors to each segment based on its starting Y value colors = black_red_cmap(norm(yvals[:-1])) # Create the LineCollection and add it to the axes lc = LineCollection(segments, colors=colors, linewidth=2) axes = plt.gca() # Get current axes instead of creating a new one axes.add_collection(lc) # Set axes limits to fit our data (LineCollection doesn't do this automatically) axes.set_xlim(xvals.min(), xvals.max()) axes.set_ylim(yvals.min(), yvals.max()) # Add a colorbar to show the Y-value to color mapping plt.colorbar(cm.ScalarMappable(norm=norm, cmap=black_red_cmap), label='Y Value') plt.show()
Quick Explanation of the Custom Colormap
I used LinearSegmentedColormap.from_list() to create a direct black-to-red gradient, which perfectly aligns with your request:
- Lowest Y values (near 0) will be pure black
- Highest Y values (near 1) will be pure red
- All values in between get a smooth transition shade
If you ever want to adjust the gradient (e.g., add more intermediate colors), you can just modify the color list in from_list().
内容的提问来源于stack exchange,提问作者Emma
相关产品推荐
相关产品推荐

