Matplotlib: add more colors to the default colors

2020-07-30 01:40发布

问题:

I just increase my sample to 12 and found axes.prop_cycle() has only 10 colors by default (I think it is tab10.). So I got IndexError: list index out of range.

My simplified code. Each sample value is represented in each row of matrix

matrix = np.random.randint(25, size=(12, 4))

for p in xrange(12):
  ax_eachp = plt.subplot2grid((protcount, 1), (p, 0), rowspan=1, colspan=1)
  ax_eachp.plot(matrix[p], color=colors[p])

Can I just add 2 more colors manually if I want to remain first 10 colors in tab10? or how to change to other qualitative color maps?

回答1:

Just as the linked question Python Matplotlib/Basemap Color Cycling shows, you may set the axes' prop_cycle to include those colors you like.

Here you can take the tab10 colors and add two more colors to the list of colors to be used in the prop_cycle.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
colors = list(plt.cm.tab10(np.arange(10))) + ["crimson", "indigo"]
ax.set_prop_cycle('color', colors)

for i in range(12):
    ax.plot([0,1],[i,i])

plt.show()

However, since in the case from the question, you anyway loop over the colors, there is actually no need for a cycler. The following produces the same result as above.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
colors = list(plt.cm.tab10(np.arange(10))) + ["crimson", "indigo"]

for i in range(12):
    ax.plot([0,1],[i,i], color=colors[i])

plt.show()