0

With this code i'm creating colorbar scales with the function make_colormap. Source:Create own colormap using matplotlib and plot color scale

import matplotlib.colors as mcolors

def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)

c = mcolors.ColorConverter().to_rgb

rvb = make_colormap([c('grey'), c('grey'), norm(3), c('sandybrown'), c('sandybrown'),
     norm(5), c('yellow'), c('yellow'), norm(10), c('navajowhite'),
     c('navajowhite'), norm(15),c('lightgreen'), c('lightgreen'),norm(20),c('lime'), c('lime'),
     norm(50),c('limegreen'), c('limegreen'),norm(80),c('forestgreen'), c('forestgreen'),norm(120),
     c('green'), c('green'),norm(160),c('darkgreen'), c('darkgreen'),norm(200),c('teal'), c('teal'),norm(300),
     c('mediumaquamarine'), c('mediumaquamarine'),norm(500),c('lightseagreen'), c('lightseagreen'),norm(700),
     c('lightskyblue'), c('lightskyblue')])

So in variable rvb i'm asssing a color to ranges of values. How can i assing a color to an specific ranges of values? For example: Grey to 0-3, sandybrown to 4-5, yellow to 6-10, etc.

The map is this:

enter image description here

Also i want to the legend show those values assigned. For example Grey color 0-3, sandybrown 4-5, etc. Something similar to this image (no need to be equal to the image, just need to show ranges with colors):

enter image description here

I also will show you part of my code when i create the map:

fig = plt.figure('map', figsize=(7,7), dpi=200)
ax = fig.add_axes([0.1, 0.12, 0.80, 0.75], projection=ccrs.PlateCarree())
plt.title('xxx')
plt.xlabel('LONGITUD') 
plt.ylabel('LATITUD') 

ax.outline_patch.set_linewidth(0.3)

l = NaturalEarthFeature(category='cultural', name='admin_0_countries', scale='50m', facecolor='none')
ax.add_feature(l, edgecolor='black', linewidth=0.25)

img = ax.scatter(lons, lats, s=7, c=ppvalues, cmap=rvb,norm=norm,
                 marker='o', transform=ccrs.PlateCarree())

handles, labels = img.legend_elements(alpha=0.2)
plt.legend(handles, labels,prop={'weight':'bold','size':10}, title='Meteorological\nStations',title_fontsize=9, scatterpoints=2);

cb = plt.colorbar(img, extend='both',
                    spacing='proportional', orientation='horizontal',
                    cax=fig.add_axes([0.12, 0.12, 0.76, 0.02]))

ax.set_extent([-90.0, -60.0, -20.0, 0.0], crs=ccrs.PlateCarree())
Javier
  • 493
  • 3
  • 15

1 Answers1

1

I don't understand the function in the question, but I have coded how to create a legend with a specified color, specified label, and specified ticks, and how to give a color bar a specified tick. Please correct the addition of colors and the tick spacing in the color bar.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.colors import LinearSegmentedColormap

list_color = ['grey','sandybrown','sandybrown','yellow',
              'navajowhite','lightgreen','lime','limegreen',
              'forestgreen','green','darkgreen','teal',
              'mediumaquamarine','lightseagreen','lightskyblue']

list_label = ['0-3', '4-5', '6-10', '11-15',
              '16-20', '21-50', '51-80', '81-120',
              '121-160', '161-200','201-300','301-500',
              '501-700','701-900','901-1200']

list_ticks = np.linspace(0, 1, 15)
vmin,vmax = 0, 1

cm = LinearSegmentedColormap.from_list('custom_cmap', list_color, N=len(list_color))
plt.imshow(np.linspace(0, 1, 25).reshape(5,5), cmap=cm, interpolation='nearest', vmin=vmin, vmax=vmax)
cbar = plt.colorbar( orientation='horizontal', extend='neither', ticks=list_ticks)
cbar.ax.set_xticklabels(list_label, rotation=45, fontsize=14)

all_patches = []
for h,l in zip(list_color, list_label):
    patch = mpatches.Patch(color=h, label=l)
    all_patches.append(patch)

plt.legend(handles=all_patches, loc='upper right', ncol=3, bbox_to_anchor=(3, 1))

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32