Fill Countries in Python Basemap

本文介绍了一种使用Python及其基本库matplotlib和pandas来绘制世界地图上足球博彩公司分布的方法。该方法避免了安装复杂的第三方包如cartopy等,并提供了一段可运行的代码示例。通过加载地理数据和定义颜色方案,可以清晰地展示不同国家的足球博彩公司数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I googled many Python methods to color countries in a world map. But most of them require additional Python packages, like cartopy, and shapelib. Because I am using Anaconda (Python 3.5) on Windows, it's not easy to install these packages. Actually, I tried many times and failed. Finally, I found a great solution from Ramiro Gómez. I listed my workable code based on Ramiro Gómez as well as the created figures.


import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from geonamescache import GeonamesCache
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from mpl_toolkits.basemap import Basemap

filename = 'bookmakers_nations.csv'
shapefile = 'ne_10m_admin_0_countries_lakes\\ne_10m_admin_0_countries_lakes'
num_colors = 27
year = '2012'
cols = ['Country Name', 'Country Code', year]
title = 'The_Distribution_of_Soccer_Bookmakers'
imgfile = 'img/{}.pdf'.format(title)

# descripton = '''
# Forest area is land under natural or planted stands of trees of at least 5 meters in situ, whether productive or not, and excludes tree stands in agricultural production systems (for example, in fruit plantations
# and agroforestry systems) and trees in urban parks and gardens. Countries without data are shown in grey. Data: World Bank - worldbank.org • Author: Ramiro Gómez - ramiro.org'''.strip()

gc = GeonamesCache()
iso3_codes = list(gc.get_dataset_by_key(gc.get_countries(), 'iso3').keys())


# df = pd.read_csv(filename, skiprows=4, usecols=cols)
df = pd.read_csv(filename, usecols=cols)
df.set_index('Country Code', inplace=True)
df = df.ix[iso3_codes].dropna() # Filter out non-countries and missing values.


values = df[year]
# cm = plt.get_cmap('Greens')
cm = plt.get_cmap('Oranges')
scheme = [cm(i / num_colors) for i in range(num_colors)]
bins = np.linspace(values.min(), values.max(), num_colors)
df['bin'] = np.digitize(values, bins) - 1
df.sort_values('bin', ascending=False).head(10)

# mpl.style.use('map')
# mpl.style.use('ggplot')
fig = plt.figure(figsize=(22, 12))

ax = fig.add_subplot(111, axisbg='w', frame_on=False)
fig.suptitle('The Distribution of Soccer Bookmakers', fontsize=30, y=.95)

# m = Basemap(lon_0=0, projection='robin')
m = Basemap(lon_0=0, projection='mill')
# m = Basemap(lon_0=0, projection='merc')
m.drawmapboundary(color='w')

m.readshapefile(shapefile, 'units', color='#444444', linewidth=.2)
for info, shape in zip(m.units_info, m.units):
    iso3 = info['ADM0_A3']
    if iso3 not in df.index:
        color = '#dddddd'
    else:
        color = scheme[df.ix[iso3]['bin']]

    patches = [Polygon(np.array(shape), True)]
    pc = PatchCollection(patches)
    pc.set_facecolor(color)
    ax.add_collection(pc)

# Cover up Antarctica so legend can be placed over it.
ax.axhspan(0, 1000 * 1800 * 4, facecolor='w', edgecolor='w', zorder=2)

# Draw color legend.
ax_legend = fig.add_axes([0.35, 0.24, 0.3, 0.03], zorder=3)
cmap = mpl.colors.ListedColormap(scheme)
cb = mpl.colorbar.ColorbarBase(ax_legend, cmap=cmap, ticks=bins, boundaries=bins, orientation='horizontal')
cb.ax.set_xticklabels([str(int(round(i, 1))) for i in bins])

# Set the map footer.
# plt.annotate(descripton, xy=(-.8, -3.2), size=14, xycoords='axes fraction')

plt.savefig(imgfile, bbox_inches='tight', pad_inches=.2)




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值