4

I would like to use a ColorFunction similar to that in Mathematica for my plots in python.

In other words, I would like to call pyplot.plot(x, y, color=c), where c is a vector, defining the color of each data point.

Is there any way to achieve this using the matplotlib library?

2 Answers 2

2

To the best of my knowledge, there is no equivalent in Matplotlib, but we can get the similar result following two steps: draw points with varied colors and draw the line.

Here is a demo.

enter image description here


The source code,

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import random

fig, ax = plt.subplots()

nrof_points = 100 
x = np.linspace(0, 10, nrof_points)
y = np.sin(x)
colors = cm.rainbow(np.linspace(0, 1, nrof_points))     # generate a bunch of colors

# draw points
for idx, point in enumerate(zip(x, y)):
    ax.plot(point[0], point[1], 'o', color=colors[idx], markersize=10)

# draw the line
ax.plot(x, y, 'k')
plt.grid()

plt.show()
Sign up to request clarification or add additional context in comments.

Comments

0

While I agree with @SparkAndShine that there is no way to parameterize the color of one line, it is possible to color many lines to create a visual effect that is largely the same. This is at the heart of a demo in the MatPlotLib documentation. However, this demo is not the simplest implementation of this principle. Here is an alternate demo based on @SparkAndShine's response:

colored sine (can't post as image since I don't have the reputation)


Source code:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

fig, ax = plt.subplots()

nrof_points = 100 
x = np.linspace(0, 10, nrof_points)
y = np.sin(x)
colors = cm.rainbow(np.linspace(0, 1, nrof_points))     # generate a bunch of colors

# draw points
for idx in range(0,np.shape(x)[0]-2,1):
    ax.plot(x[idx:idx+1+1], y[idx:idx+1+1], color=colors[idx])

# add a grid and show
plt.grid()

plt.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.