简体   繁体   中英

How to make matplotlib cycle through qualitative cmap?

I'm afraid is isn't a reproducible example but I'll try to clearly explain my problem.

I have some geographic data that has a 'community' label that is a number, although it's just a categorical thing. There are about 100 communities, and it seems the labelling sequence is spatial; ie. consecutive labels are near to each other. I want to visualize the data using one of the qualitative colormaps, eg. 'Paired' (cf. https://matplotlib.org/stable/tutorials/colors/colormaps.html ), which only has 12 colors, but as there are never (or at least rarely) more than twelve communities in a small area, that would not be a problem if matplotlib cycled through the colors, so that '01' gets the first color, '02' the second, ...; and only repeating at '13'.

Except instead the default seems to be to squeeze nearby labels together with the same color rather than cycling, so that '01','02','03, ..., have the same color; as do '13', '14', '15'... and so on.

This seems like it should be a simple thing to change, but I seem to lack the proper knowledge of matplotlib's inner workings to work out exactly what to do.

There's similar question here that suggests I just need to do something with set_prop_cycle , but I'm still not getting what I want...

@Peter Prescott, if you haven't found a solution to your problem yet, I think just creating a custom colormap by adding the X sets of colors you need will do the trick.

X = math.ceil(N / M), M being the number of colors in your base colormap.

In your example, N = 100, M = 12, X = 9.

Simple application:

cmap = plt.cm.tab20                           # get a specific colormap
cmaplist = cmap.colors                        # extract all colors
cmaplistext = cmaplist + cmaplist             # repeat X times, here X = 2
customMap = matplotlib.colors.LinearSegmentedColormap.from_list(
                                'Custom cmap', cmaplistext, N)
plt.imshow(data, customMap)
    

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