74

How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this

import numpy as np
import matplotlib.pyplot as plt

fig=plt.figure(i)
ax=plt.gca()
colormap = plt.get_cmap('jet')
ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)])

but is there some way to set the same set of colors for all plots, including subplots?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Katt
  • 957
  • 1
  • 8
  • 11

3 Answers3

86

Sure! Either specify axes.color_cycle in your .matplotlibrc file or set it at runtime using matplotlib.rcParams or matplotlib.rc.

As an example of the latter:

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

# Set the default color cycle
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "k", "c"]) 

x = np.linspace(0, 20, 100)

fig, axes = plt.subplots(nrows=2)

for i in range(10):
    axes[0].plot(x, i * (x - 10)**2)

for i in range(10):
    axes[1].plot(x, i * np.cos(x))

plt.show()

enter image description here

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • 4
    For those who want more color: mpl.rcParams['axes.color_cycle'] = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black', 'purple', 'pink', 'brown', 'orange', 'teal', 'coral', 'lightblue', 'lime', 'lavender', 'turquoise', 'darkgreen', 'tan', 'salmon', 'gold'] – Ludo Schmidt Jul 10 '18 at 13:32
  • 3
    `axes.color_cycle is not a valid rc parameter` – endolith Sep 11 '19 at 14:41
  • 2
    @endolith [in version 1.5 and later, the new key is `axes.prop_cycle`](https://stackoverflow.com/a/37211181/52074) – Trevor Boyd Smith Nov 25 '19 at 20:06
  • 1
    @LudoSchmidt i justed spent like 4 hours messing with color cycles. but your list is better. good job. – Trevor Boyd Smith Nov 25 '19 at 20:06
  • 1
    How can I set it back to default without having to restart the kernel? I mean, say I just run `mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "k", "c"])` and plot a bunch of plots. Now I want to restore the default matplotlib colors and plot another bunch of plots. How do I do it? – Sergio Polimante Oct 25 '21 at 22:57
54

Starting from matplotlib 1.5, mpl.rcParams['axes.color_cycle'] is deprecated. You should use axes.prop_cycle:

import matplotlib as mpl
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "#e94cdc", "0.7"]) 
volodymyr
  • 7,256
  • 3
  • 42
  • 45
4

In the version of 2.1.0, the below works for me, using set_prop_cycle and module cycler

from cycler import cycler
custom_cycler = (cycler(color=['r','b','m','g']))
ax.set_prop_cycle(custom_cycler)

you can add additional line attribute

custom_cycler = (cycler(color=['r','b','m','g']) + cycler(lw=[1,1,1,2]))

'ax' comes from ax=plt.axes() or any axes generator

Joonho Park
  • 511
  • 5
  • 17