Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib - change marker color along plot line

I would like to plot a 2d data set with matplotlib such that the marker color for each data point is different. I found the example on multicolored lines (http://matplotlib.org/examples/pylab_examples/multicolored_line.html). However, this does not seem to work when plotting a line with markers.

The solution I came up with individually plots every point:

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

# The data
x = np.linspace(0, 10, 1000)
y = np.sin(2 * np.pi * x)

# The colormap
cmap = cm.jet

# Create figure and axes
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(1, 1, 1)

# Plot every single point with different color
for i in range(len(x)):
    c = cmap(int(np.rint(x[i] / x.max() * 255)))
    ax.plot(x[i], y[i], 'o', mfc=c, mec=c)
    ax.set_xlim([x[0], x[-1]])
    ax.set_ylim([-1.1, 1.1])
    ax.set_xlabel('x')
    ax.set_ylabel('y')

plt.draw()
plt.show()

# Save the figure
fig.savefig('changing_marker_color.png', dpi=80)

The resulting plot looks like as it should but the plotting gets really slow and I need it quite fast. Is there a clever trick to speed up the plotting?

like image 407
Daniel Avatar asked Sep 04 '13 16:09

Daniel


People also ask

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

How do I change the color of my plot line?

Change the color of a line Select the line that you want to change. If you want to change multiple lines, select the first line, and then press and hold CTRL while you select the other lines. On the Format tab, click the arrow next to Shape Outline, and then click the color that you want.


1 Answers

I believe you can achieve this with ax.scatter:

# The data
x = np.linspace(0, 10, 1000)
y = np.sin(2 * np.pi * x)

# The colormap
cmap = cm.jet

# Create figure and axes
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(1, 1, 1)

c = np.linspace(0, 10, 1000)
ax.scatter(x, y, c=c, cmap=cmap)

Scatter accepts c as a sequence of floats which will be mapped to colors using the cmap.

enter image description here

Using timeit I get a 10 fold decrease in time (about 1.25 secs for the original method and 76.8 ms here)

like image 137
Greg Avatar answered Oct 16 '22 08:10

Greg