Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change colour of curve according to its y-value in matplotlib [duplicate]

I'm trying to replicate the style of the attached figure using matplotlib's facilities.

Curves whose colour change with height

Basically, I want to change the colour of the curve according to its y-value using matplotlib.

like image 954
Joey Dumont Avatar asked Nov 23 '13 16:11

Joey Dumont


People also ask

How do you change the color of a graph in 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.

How do I plot multiple Y values in Matplotlib?

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?

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.

How do I change the marker color in Matplotlib?

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).


1 Answers

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))

colors

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:

  • The color vector should range between 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.
  • I used edgecolor='none' because by default the scatter markers have a black outline which makes the it look less like a uniform line.
  • If your data is spaced too far, you'll have to interpolate the data if you don't want gaps between markers.

more colors

like image 141
askewchan Avatar answered Sep 20 '22 15:09

askewchan