I'm trying to replicate the style of the attached figure using matplotlib's facilities.
Basically, I want to change the colour of the curve according to its y-value using matplotlib.
The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.
MatPlotLib with Python To make a scatter plot with multiple Y values for each X, we can create x and y data points using numpy, zip and iterate them together to create the scatter plot.
How do you iterate colors in python? # Iterate through a string S = 'python' for x in S: print(x) # Prints p y t h o n. # Break the loop at 'blue' colors = ['red', 'green', 'blue', 'yellow'] for x in colors: if x == 'blue': break print(x) # Prints red green.
All of the line properties can be controlled by keyword arguments. For example, you can set the color, marker, linestyle, and markercolor with: plot(x, y, color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12).
The plot you've shown doesn't have the color set by the vertical axis of the plot (which is what I would consider the y-value). Instead, it just has 8 different plots overlain, each with a different color, without stating what the color means.
Here's an example of something that looks like your plot:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
# some fake data:
x = np.linspace(0, 2*np.pi, 1000)
fs = np.arange(1, 5.)
ys = np.sin(x*fs[:, None])
for y, f in zip(ys, fs):
plt.plot(x, y, lw=3, c=cm.hot(f/5))
If you actually want the color of one line to change with respect to its value, you have to kind of hack it, because any given Line2D
object can only have one color, as far as I know. One way to do this is to make a scatter plot, where each dot can have any color.
x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(2*x)
plt.scatter(x,y, c=cm.hot(np.abs(y)), edgecolor='none')
Notes:
0
and 1
, so if y.max() > 1
, then normalize by it: c=cm.hot(y/y.max())
and make sure it's all positive.edgecolor='none'
because by default the scatter
markers have a black outline which makes the it look less like a uniform line.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With