简体   繁体   English

Python Matplotlib添加Colorbar

[英]Python Matplotlib add Colorbar

i've got a problem using MatlobLib with "Custom" Shapes from a shapereader. 我使用MatlobLib和shapereader的“Custom”形状有问题。 Importing and viewing inserted faces works fine, but i'm not able to place a colorbar on my figure. 导入和查看插入的面部工作正常,但我无法在我的图上放置颜色条。

I already tried several ways from the tutorial, but im quite sure there is a smart solution for this problem. 我已经从教程中尝试了几种方法,但我非常确定这个问题有一个智能解决方案。

maybe somebody can help me, my current code is attached below: 也许有人可以帮助我,我现在的代码附在下面:

from formencode.national import pycountry
import itertools
from matplotlib import cm, pyplot
from matplotlib import 
from mpl_toolkits.basemap import Basemap
from numpy.dual import norm
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import matplotlib as mpl
import matplotlib.colors as colors
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import numpy as np

def draw_map_for_non_normalized_data_with_alpha2_counrty_description(data, title=None):

m = Basemap()
ax = plt.axes(projection=ccrs.PlateCarree())

list = []
sum = 0
for key in data:
    sum += data[key]

for key in data.keys():
    new_val = (data[key]+0.00)/sum
    list.append(new_val)
    data[key] = new_val

#===========================================================================
# print str(min(list))
# print str(max(list))
#===========================================================================

cmap = mpl.cm.cool
colors = matplotlib.colors.Normalize(min(list)+0.0, max(list)+0.0)

labels = []
features = []
for country in shpreader.Reader(shapename).records():
    a3_code = country.attributes["gu_a3"]
    try :
        a2_code =  pycountry.countries.get(alpha3=a3_code).alpha2
    except:
        a2_code = ""

    if a2_code in data:
        val = data[a2_code]

        color = cm.jet(norm(val))

        print str(val) + " value for color: " + str(color)

        labels.append(country.attributes['name_long'])
        feat = ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=color, label=country.attributes['name_long'])

        features.append(feat)   
#ax.legend(features, labels, loc='upper right')
#===========================================================================
# fig = pyplot.figure(figsize=(8,3))    
# ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
#===========================================================================

#cbar = m.colorbar(location='bottom')
cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,norm=colors,orientation='horizontal')
cb1.set_label('foo')

m.drawcoastlines()
m.drawcountries()
if title:
    plt.title(title)

plt.show() 

as you can see inside the code, i already tried several ways, but none of them worked for me. 正如你在代码中看到的那样,我已经尝试了几种方法,但它们都没有为我工作。

maybe somebody has "the" hint for me. 也许有人对我有“暗示”的暗示。

thanks for help, 感谢帮助,

kind regards 亲切的问候

As mentioned in the comments above, i would think twice about mixing Basemap and Cartopy , is there a specific reason to do so? 正如上面的评论所提到的,我会考虑混合BasemapCartopy ,是否有特定的理由这样做? Both are basically doing the same thing, extending Matplotlib with geographical plotting capabilities. 两者基本上都在做同样的事情,将Matplotlib扩展到地理绘图功能。 Both are valid to use, they both have their pro's and con's. 两者都有效使用,他们都有他们的专业和骗局。

In your example you have a Basemap axes m , a Cartopy axes ax and you are using the Pylab interface by using plt. 在您的示例中,您有一个底图轴m ,一个Cartopy轴ax并且您使用plt.使用Pylab接口plt. which operates on the currently active axes. 它在当前活动的轴上运行。 Perhaps it theoretically possible, but it seems prone to errors to me. 也许它在理论上是可能的,但它似乎容易出错。

I cant modify your example to make it work, since the data is missing and your code is not valid Python, the indentation for the function is incorrect for example. 我无法修改您的示例以使其工作,因为数据丢失且您的代码不是有效的Python,例如该函数的缩进不正确。 But here is a Cartopy-only example showing how you can plot a Shapefile and use the same cmap/norm combination to add a colorbar to the axes. 但这里是一个仅限Cartopy的示例,显示如何绘制Shapefile并使用相同的cmap/norm组合向轴添加颜色条。

One difference with your code is that you provide the axes containing the map to the ColorbarBase function, this should be a seperate axes specifically for the colorbar. 与代码的一个不同之处在于,您将包含地图的轴提供给ColorbarBase函数,这应该是专门用于ColorbarBase的单独轴。

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib as mpl
import cartopy.io.shapereader as shpreader

fig, ax = plt.subplots(figsize=(12,6), 
                       subplot_kw={'projection': ccrs.PlateCarree()})

norm = mpl.colors.Normalize(vmin=0, vmax=1000000)
cmap = plt.cm.RdYlBu_r

for n, country in enumerate(shpreader.Reader(r'D:\ne_50m_admin_0_countries_lakes.shp').records()):

    ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                      facecolor=cmap(norm(country.attributes['gdp_md_est'])),
                      label=country.attributes['name'])

ax.set_title('gdp_md_est')

cax = fig.add_axes([0.95, 0.2, 0.02, 0.6])
cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, spacing='proportional')
cb.set_label('gdp_md_est')

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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