vaab / colour

Python color representations manipulation library (RGB, HSL, web, ...)
BSD 2-Clause "Simplified" License
319 stars 41 forks source link

Explanation of how to use this package in combination with matplotlib? #43

Open Omer80 opened 6 years ago

Omer80 commented 6 years ago

Hi, I am trying to create a plot in which each line is picked from a colormap, like in this code:

import matplotlib.pylab as plt
import numpy as np
x = np.linspace(0,10,100)
n_lines = 3
cl = plt.cm.cool(np.linspace(0, 1, n_lines))
for i in range(3):
    plt.plot(x,x**(i+1),color=cl[i])
plt.show()

How can I use colour package in order to create a custom gradient and use it with matplotlib? I tried to create a gradient from brown to green in this way:

from colour import Color
brown = Color("brown")
cl = list(brown.range_to(Color("green"),3))

But it gave me error when plugging cl to the code I've given above..

Helveg commented 4 years ago

From what I can tell, skimping over your example it will most likely be because matplotlib doesn't handle the Color objects returned from the brown.range_to generator. You should try converting the Color objects to strings before passing them into matplotlib:

cl = list(map(str, brown.range_to(Color("green"),3)))
corndogit commented 2 years ago

Here's an example of how I made a colour range to fit to a plot of the Hilbert curve.

start_colour = Color("#000033")
end_colour = Color("#0000FF")
colour_range = list(start_colour.range_to(end_colour, len(distances)))

In the above, len(distances) is the length of my Hilbert curve, so the number of colours in the range matches the number of line segments. I then wrote a loop which plots each line segment with the colour from the colour range. Note that you have to use str() on the colour range list elements, as they are still Color objects, not strings.

plt.plot(xpoints, ypoints, c=str(colour_range[count]))

And the result:
Hilbert curve with colour gradient