【发布时间】:2014-10-19 18:29:05
【问题描述】:
我在使用来自 shapereader 的“自定义”形状的 MatlobLib 时遇到问题。导入和查看插入的面孔工作正常,但我无法在我的身材上放置颜色条。
我已经尝试了教程中的几种方法,但我很确定这个问题有一个聪明的解决方案。
也许有人可以帮助我,我当前的代码附在下面:
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()
正如您在代码中看到的那样,我已经尝试了几种方法,但没有一个对我有用。
也许有人对我有“提示”。
感谢您的帮助,
亲切的问候
【问题讨论】:
-
你的代码对我来说很模糊,它不是一个完整的例子。你在用什么模块?看起来您将
Basemap和Cartopy混合在一起,这似乎已经有点棘手。如果你这样做,它可能有助于相应地标记你的帖子。 -
感谢您的评论,我添加了导入(抱歉,它们有点搞砸了 :( ) - 是的,它的 Cartopy 和底图,因为我已经按照这个“教程”完成了:stackoverflow.com/questions/13397022/…,还有其他方法可以更轻松地做到这一点吗?
标签: python matplotlib legend shapes cartopy