Python Matplotlib/Basemap Color Cycling

2019-06-14 13:49发布

I'm new to Python and the other programs and I'm attempting to plot 21 members of an ensemble forecast using for loops over the ensemble members, each one having a dedicated number 1-21. When I plot the map, the members all come up blue. I've done some research on colormaps and found that the default maps are not indexed, i.e. I can't call colormap[1] as if it were a list or array. Are there any indexed colormaps out there, or is there any way around this? Simply put, I want to cycle through colors, a different one for each forecast member, using simple numerics.

1条回答
Emotional °昔
2楼-- · 2019-06-14 14:10

You could use ax.set_prop_cycle to specify a list of colors to cycle through.

Colormaps are callable, so an easy way to generate colors is to pass an sequence of floats between 0 and 1 to a colormap, which will then return an array of RGBA colors.

For example,

In [93]: jet = plt.cm.jet

In [94]: jet([0,0.5,1])
Out[94]: 
array([[ 0.        ,  0.        ,  0.5       ,  1.        ],
       [ 0.49019608,  1.        ,  0.47754586,  1.        ],
       [ 0.5       ,  0.        ,  0.        ,  1.        ]])

import matplotlib.pylab as plt
import matplotlib.rcsetup as rcsetup
import numpy as np

jet = plt.cm.jet
fig, ax = plt.subplots()
N = 20
idx = np.linspace(0, 1, N)
ax.set_prop_cycle(rcsetup.cycler('color', jet(idx)))
x = np.linspace(0, 100, 200)
for i in range(1, N+1):
    ax.plot(x, np.sin(x)+i)
ax.set_ylim(0, N+1)
plt.show()

enter image description here

查看更多
登录 后发表回答