How to create colour gradient in Python?

A simple answer I have not seen yet is to just use the colour package.

Install via pip

pip install colour

Use as so:

from colour import Color
red = Color("red")
colors = list(red.range_to(Color("green"),10))
    
# colors is now a list of length 10
# Containing: 
# [<Color red>, <Color #f13600>, <Color #e36500>, <Color #d58e00>, <Color #c7b000>, <Color #a4b800>, <Color #72aa00>, <Color #459c00>, <Color #208e00>, <Color green>]

Change the inputs to any colors you want. As noted by @zelusp, this will not restrict itself to a smooth combination of only two colors (e.g. red to blue will have yellow+green in the middle), but based on the upvotes it's clear a number of folks find this to be a useful approximation


If you just need to interpolate in between 2 colors, I wrote a simple function for that. colorFader creates you a hex color code out of two other hex color codes.

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

def colorFader(c1,c2,mix=0): #fade (linear interpolate) from color c1 (at mix=0) to c2 (mix=1)
    c1=np.array(mpl.colors.to_rgb(c1))
    c2=np.array(mpl.colors.to_rgb(c2))
    return mpl.colors.to_hex((1-mix)*c1 + mix*c2)

c1='#1f77b4' #blue
c2='green' #green
n=500

fig, ax = plt.subplots(figsize=(8, 5))
for x in range(n+1):
    ax.axvline(x, color=colorFader(c1,c2,x/n), linewidth=4) 
plt.show()

result:

simple color mixing in python

update due to high interest:

colorFader works now for rgb-colors and color-strings like 'red' or even 'r'.