2

In matplotlib, I can have a scatter plot with varying marker color given in clist. Note: the size of clist is the same as ydata, i.e., the color of each marker is specified separately.

plt.scatter(xdata, ydata, marker='o', c=clist)

Can I have something similar with plt.plot?

2 Answers2

2

The equivalent to

plt.scatter(xdata, ydata, marker='o', c=clist)

would be

plt.gca().set_prop_cycle(plt.cycler("color", clist))
plt.plot(np.atleast_2d(xdata), np.atleast_2d(ydata), marker="o")

Of course you can also use a loop. And in general, I would recommend just staying with scatter in such case.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

This is one solution based on the trick shown here for marker.

import itertools
import matplotlib.pyplot as plt

colors = itertools.cycle(('r', 'g', 'b', 'c', 'k')) 

for n in range(5):
    plt.plot(n, n**2, marker = 'o', color=next(colors), linestyle='')

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • The size of `clist` is the same as `ydata`, i.e., the color of each marker is specified separately. Will this work if I use my `clist` instead of your `colors`? Would this have a reasonable performance for, say, thousands of data points? – sancho.s ReinstateMonicaCellio Dec 05 '19 at 16:02
  • @sancho.sReinstateMonica : It should work if you replace `('r', 'g', 'b', 'c', 'k')` by your list in the same `(....)` format. For the performance, I would simply use `%timeit` to measure the timings – Sheldore Dec 05 '19 at 16:06
  • [`scatter`](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.scatter.html) accepts for `c`: 1) A single color format string. 2) A sequence of color specifications of length n. 3) A sequence of n numbers to be mapped to colors using cmap and norm. 4) A 2-D array in which the rows are RGB or RGBA. while [`plot`](https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html) accepts for `color` "any matplotlib color". Would this be the same? Or should I convert before my `clist` (which will be, mainly, a list of `float`s)? – sancho.s ReinstateMonicaCellio Dec 06 '19 at 09:37