Python Matplotlib添加Colorbar [英] Python Matplotlib add Colorbar

查看:52
本文介绍了Python Matplotlib添加Colorbar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MatlobLib和来自shapereader的自定义"形状时出现问题.导入和查看插入的脸部效果很好,但是我无法在图形上放置颜色条.

i've got a problem using MatlobLib with "Custom" Shapes from a shapereader. 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.

也许有人为我提供了"the"提示.

maybe somebody has "the" hint for me.

感谢帮助,

亲切的问候

推荐答案

如上面的评论所述,我会三思而后行地将 Basemap Cartopy 混合在一起这样做的具体原因是什么?两者基本上都在做相同的事情,通过地理绘图功能扩展了Matplotlib.两者都可以使用,它们都有各自的优点和缺点.

As mentioned in the comments above, i would think twice about mixing Basemap and Cartopy, is there a specific reason to do so? Both are basically doing the same thing, extending Matplotlib with geographical plotting capabilities. Both are valid to use, they both have their pro's and con's.

在您的示例中,您有一个底图坐标轴 m ,一个Cartopy坐标轴 ax ,并且您正在通过 Pylab 界面使用请在当前活动的轴上运行.从理论上讲也许是可行的,但对我来说似乎容易出错.

In your example you have a Basemap axes m, a Cartopy axes ax and you are using the Pylab interface by using plt. which operates on the currently active axes. Perhaps it theoretically possible, but it seems prone to errors to me.

我无法修改您的示例以使其工作,因为数据丢失并且您的代码无效的Python,例如,该函数的缩进不正确.但是,这是一个仅用于Cartopy的示例,显示了如何绘制 Shapefile 并使用相同的 cmap/norm 组合向轴添加颜色栏的示例.

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. 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.

与代码的不同之处在于,您将包含映射的轴提供给 ColorbarBase 函数,这应该是专门用于颜色栏的单独轴.

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.

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

这篇关于Python Matplotlib添加Colorbar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆