世界地图
话不多说,上代码,超级简单。这个题把国家分为三类,每种类型的国家涂上不同的颜色,cn是中国,但是涂色时发现台湾没涂上颜色,于是把tw加上
图片如下
代码如下:
import pygal.maps.world
worldmap_chart = pygal.maps.world.World()
worldmap_chart.title = 'Some countries'
worldmap_chart.add('stable', ['ch', 'mv', 'cn','tw'])
worldmap_chart.add('vulnerable', ['ga', 'by', 'pe', 'iq', 'sy',
'mx', 'nz', 'ng', 'ca', 'no',
'dk', 'is', 'au', 'de'])
worldmap_chart.add('fragile', ['zw', 'af','sd','td'])
worldmap_chart.render_to_file('bar_chart.svg')
运行完后生成一个名为bar_chart.svg的文件,右键,复制路径(copy path),在浏览器中打开
这个图是2019年美赛建模c题用到的图,五个州涂上颜色,从文件中读取数据根据数据确定圆圈大小。代码如下:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm
# 绘制基础地图,选择绘制的区域,因为是绘制美国地图,故选取如下经纬度,lat_0和lon_0是地图中心的维度和经度
map = Basemap(projection='stere',lat_0=90,lon_0=-105,\
llcrnrlat=23.41 ,urcrnrlat=45.44,\
llcrnrlon=-118.67,urcrnrlon=-64.52,\
rsphere=6371200.,resolution='l',area_thresh=10000)
map.drawmapboundary() # 绘制边界
map.drawstates()
map.drawcoastlines()
map.drawcountries()
map.drawcounties()
parallels = np.arange(0.,90,10.)
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # 绘制纬线
meridians = np.arange(-110.,-60.,10.)
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) # 绘制经线
posi=pd.read_csv("D:\\data1.csv") # 读取数据
## 原始数据有3228组数据,我只选择了180个城市的数据
lat = np.array(posi["lat"][0:10]) # 获取维度之维度值
lon = np.array(posi["lon"][0:10]) # 获取经度值
pop = np.array(posi["pop"][0:10]) # 获取人口数,转化为numpy浮点型
size=(pop/np.max(pop))*1000 # 绘制散点图时图形的大小,如果之前pop不转换为浮点型会没有大小不一的效果
x,y = map(lon,lat)
map.scatter(x,y,s=size) # 也可以使用Basemap的methord本身的scatter
#plt.title('America')
plt.show()
从文件中读取数据,文件放在 D盘,文件内容如下,用wps表格编辑,另存为csv格式。
美国地图,不过瘾,再来一个
from __future__ import (absolute_import, division, print_function)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.colors import rgb2hex, Normalize
from matplotlib.patches import Polygon
from matplotlib.colorbar import ColorbarBase
fig, ax = plt.subplots()
m = Basemap(llcrnrlon=-119,llcrnrlat=20,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
m_ = Basemap(llcrnrlon=-190,llcrnrlat=20,urcrnrlon=-143,urcrnrlat=46,
projection='merc',lat_ts=20) # do not change these numbers
shp_info = m.readshapefile('st99_d00','states',drawbounds=True,
linewidth=0.45,color='gray')
shp_info_ = m_.readshapefile('st99_d00','states',drawbounds=False)
popdensity = {
'New Jersey': 1,
'Rhode Island': 1,
'Massachusetts': 1,
'Connecticut': 1,
'Maryland': 1,
'New York': 1,
'Delaware': 1,
'Florida': 1,
'Ohio': 250,
'Pennsylvania': 300,
'Illinois': 1,
'California': 1,
'Hawaii': 1,
'Virginia': 50,
'Michigan': 1,
'Indiana': 1,
'North Carolina': 1,
'Georgia': 1,
'Tennessee': 1,
'New Hampshire': 1,
'South Carolina': 1,
'Louisiana': 1,
'Kentucky': 10,
'Wisconsin': 1,
'Washington': 1,
'Alabama': 1,
'Missouri': 1,
'Texas': 1,
'West Virginia': 200,
'Vermont': 1,
'Minnesota': 1,
'Mississippi': 1,
'Iowa': 1,
'Arkansas': 1,
'Oklahoma': 1,
'Arizona': 1,
'Colorado': 1,
'Maine': 1,
'Oregon': 1,
'Kansas': 1,
'Utah': 1,
'Nebraska': 1,
'Nevada': 1,
'Idaho': 1,
'New Mexico': 1,
'South Dakota': 1,
'North Dakota': 1,
'Montana': 1,
'Wyoming': 1,
'Alaska': 1}
colors={
}
statenames=[]
cmap = plt.cm.hot_r
vmin = 0;
vmax = 450
norm = Normalize(vmin=vmin, vmax=vmax)
for shapedict in m.states_info:
statename = shapedict['NAME']
if statename not in ['District of Columbia','Puerto Rico']:
pop = popdensity[statename]
colors[statename] = cmap(np.sqrt((pop-vmin)/(vmax-vmin)))[:3]
statenames.append(statename)
for nshape,seg in enumerate(m.states):
if statenames[nshape] not in ['Puerto Rico', 'District of Columbia']:
color = rgb2hex(colors[statenames[nshape]])
poly = Polygon(seg,facecolor=color,edgecolor=color)
ax.add_patch(poly)
AREA_1 = 0.005
AREA_2 = AREA_1 * 30.0
AK_SCALE = 0.19
HI_OFFSET_X = -1900000
HI_OFFSET_Y = 250000
AK_OFFSET_X = -250000
AK_OFFSET_Y = -750000
for nshape, shapedict in enumerate(m_.states_info):
if shapedict['NAME'] in ['Alaska', 'Hawaii']:
seg = m_.states[int(shapedict['SHAPENUM'] - 1)]
if shapedict['NAME'] == 'Hawaii' and float(shapedict['AREA']) > AREA_1:
seg = [(x + HI_OFFSET_X, y + HI_OFFSET_Y) for x, y in seg]
color = rgb2hex(colors[statenames[nshape]])
elif shapedict['NAME'] == 'Alaska' and float(shapedict['AREA']) > AREA_2:
seg = [(x*AK_SCALE + AK_OFFSET_X, y*AK_SCALE + AK_OFFSET_Y)\
for x, y in seg]
color = rgb2hex(colors[statenames[nshape]])
poly = Polygon(seg, facecolor=color, edgecolor='gray', linewidth=.45)
ax.add_patch(poly)
light_gray = [0.8]*3 # define light gray color RGB
x1,y1 = m_([-190,-183,-180,-180,-175,-171,-171],[29,29,26,26,26,22,20])
x2,y2 = m_([-180,-180,-177],[26,23,20]) # these numbers are fine-tuned manually
m_.plot(x1,y1,color=light_gray,linewidth=0.8) # do not change them drastically
m_.plot(x2,y2,color=light_gray,linewidth=0.8)
ax_c = fig.add_axes([0.9, 0.1, 0.03, 0.8])
cb = ColorbarBase(ax_c,cmap=cmap,norm=norm,orientation='vertical',
label=r'[population per $\mathregular{km^2}$]')
plt.show()
当然,这种图片是根据州的形状涂颜色的,不能像上一张图一样定位一个点图颜色。这种图需要加载三个文件,是从GitHub上找的,百度网盘地址
https://pan.baidu.com/s/1gXh9kjeXLcgao8nV_bBsrg