简体   繁体   中英

How to add a new color in matplotlib graph (or use colormaps)?

I have seen several similar question but none which answers my precise question, so please bear with it before marking it duplicate.

I have to plot n lines on a graph. The standard value of n is 10 but it can vary. Previously, I used

ax.set_color_cycle([plt.cm.Accent(i) for i in np.linspace(0, 1, limit)])

Which works well for me.

However, this method has depreciated as of late, and my program gives a warning for the same to use set_prop_cycle

I wasn't able to find any example in the documentation http://matplotlib.org/api/axes_api.html that suits my needs of uses a colour bar like accent or hot or cool etc.

Update

Sample code for testing:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
limit=10
ax.set_color_cycle([plt.cm.Accent(i) for i in np.linspace(0, 1, limit)])
for limit in range(1,limit+1):
       x=np.random.randint(10, size=10)
       y=limit*x
       plt.plot(x,y,lw=2, label=limit)
       plt.legend(loc='best')

What this shows me is: 在此输入图像描述

The question is how can I use a colormap to chose between different shades of a color or the sort? http://matplotlib.org/users/colormaps.html

You need a slightly different formulation in order to make use of the more generic set_prop_cycle . You have to create a cycler for the argument 'color' with plt.cycler and for the rest do it exactly as you did before:

import matplotlib.pyplot as plt
import numpy as np

limit=10

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', plt.cm.Accent(np.linspace(0, 1, limit))))
for limit in range(1,limit+1):
    x=np.random.randint(10, size=10)
    y=limit*x
    plt.plot(x,y,lw=2, label=limit)
    plt.legend(loc='best')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM