【问题标题】:How to show ranges of values with a color assigned in the legend?如何使用图例中分配的颜色显示值范围?
【发布时间】:2021-04-06 13:21:21
【问题描述】:

使用此代码,我正在使用函数 make_colormap 创建颜色条比例。来源: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')])

所以在变量rvb 中,我将颜色分配给值范围。如何将颜色分配给特定范围的值?例如:灰色到0-3,沙棕色到4-5,黄色到6-10等。

地图是这样的:

我还想在图例中显示分配的那些值。例如灰色 0-3、沙褐色 4-5 等。 类似于这张图片的东西(不需要和图片一样,只需要用颜色显示范围):

我还会在创建地图时向您展示我的部分代码:

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())

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:

    我不明白问题中的函数,但我编写了如何创建具有指定颜色、指定标签和指定刻度的图例,以及如何为颜色条指定指定刻度。请更正颜色栏中的颜色添加和刻度间距。

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 2018-07-07
      • 1970-01-01
      • 2014-01-01
      • 2016-09-18
      • 2011-08-15
      • 1970-01-01
      • 2019-01-25
      相关资源
      最近更新 更多