ORIGIN

Draw map with Color

Python 2 mins392 words

Last article, we learned how to draw a uncolored map with python. Now, we are going to fill our country with beautiful colors.

Unified Color

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import matplotlib.pyplot as plot
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon

plot.figure(figsize=(14,6))
m = Basemap(
llcrnrlon=77,
llcrnrlat=14,
urcrnrlon=140,
urcrnrlat=51,
projection='lcc',
lat_1=33,
lat_2=45,
lon_0=100
)

m.readshapefile(r'CHN_adm/CHN_adm1', 'states', drawbounds=True)
ax = plot.gca()
for nshape, seg in enumerate(m.states):
poly = Polygon(seg, facecolor='DeepSkyBlue')
ax.add_patch(poly)

m.readshapefile(r'TWN_adm/TWN_adm1', 'states', drawbounds=True)
ax = plot.gca()
for nshape, seg in enumerate(m.states):
poly = Polygon(seg, facecolor='DeepSkyBlue')
ax.add_patch(poly)

plot.show()

在这里插入图片描述

China population graph

For further use, It will also use pandas , so install it.

1
pip install pandas --user

And here is the population data http://www.stats.gov.cn/tjsj/pcsj/rkpc/6rp/indexce.htm

After download it, modify the file until it looks like this:

在这里插入图片描述

The most important thing is that don’t forget to delete the space between province names!!!! This is important because I stuck because of this for a day.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import matplotlib.pyplot as plot
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.colors import rgb2hex
import pandas as pd
import numpy as np

plot.figure(figsize=(14,6))
m = Basemap(
llcrnrlon=77,
llcrnrlat=14,
urcrnrlon=140,
urcrnrlat=51,
projection='lcc',
lat_1=33,
lat_2=45,
lon_0=100
)

m.readshapefile(r'../CHN_adm/CHN_adm1', 'states', drawbounds=True)

df = pd.read_excel(r'../A0101a.xls')
df['省名'] = df.地区.str[:2]
df.set_index('省名', inplace=True)
statenames=[]
colors={}
cmap = plot.cm.Blues
vmax = 100000000
vmin = 3000000
for shapedict in m.states_info:
statename = shapedict['NL_NAME_1']
p = statename.split('|')
if len(p) > 1:
s = p[1]
else:
s = p[0]
s = s[:2]
if s == '黑龍':
s = '黑龙'
statenames.append(s)

# print(df['人口数'])
pop = df['人口数'][s]
colors[s] = cmap(np.sqrt((pop - vmin) / (vmax - vmin)))[:3]

ax = plot.gca()
for nshape, seg in enumerate(m.states):
color = rgb2hex(colors[statenames[nshape]])
poly = Polygon(seg, facecolor=color, edgecolor=color)
ax.add_patch(poly)

plot.show()

在这里插入图片描述

Sooooooooooo beautiful!!!

TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|