程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Actual combat | Python easily realizes map visualization (with detailed source code)

編輯:Python

Python There are many map visualization libraries ,Matplotlib Although the library is very powerful , But you can only make static maps . And today I'm going to talk about the interactive map library , Respectively pyecharts、folium, Master these two libraries , It can basically solve your map visualization needs .

pyecharts

First , We must talk about the powerful pyecharts library , Easy to use and cool , You can make almost any chart .pyecharts Yes v0.5 and v1 Two versions , The two are incompatible , Abreast of the times v1 Version started to support chained calls , use options Configuration chart .pyecharts In making maps , contain Map、Geo and Bmap Three types of , Use Map Class support world 、 Country 、 Four level maps of provinces, cities, districts and counties , It shall be installed independently before use .so,pip they !

1pip install pyecharts
2pip install echarts-countries-pypkg
3pip install echarts-china-provinces-pypkg
4pip install echarts-china-cities-pypkg
5pip install echarts-china-counties-pypkg

pip After that , Look at the pyecharts edition .

1import pyecharts
2print(pyecharts.__version__)

Beyond all doubt , It must be the latest version , The version number is 1.6.2.

One Map

Before making a map , First, we need data , I started from Wind The database is exported to all provinces of the country GDP Total data , Name it GDP.xlsx, As shown in the figure below .

With data , We can use python It's starting to work , First put the required Library import once .

1import pandas as pd #pandas Is a powerful data processing library
2from pyecharts.charts import Map
3from pyecharts import options as opts 

use pandas Read GDP.xlsx, extract 2019 Provinces in GDP Take the data , Let's make a map . Pay attention here zip() function , It is used to take iteratable objects as parameters , Package the corresponding elements in the object into tuples , And then return the objects made up of these tuples .

1data = pd.read_excel('GDP.xlsx')
2province = list(data["province"])
3gdp = list(data["2019_gdp"])
4list = [list(z) for z in zip(province,gdp)]

Let's print list, Long like this :

In fact, it is the data structure of the nested list in the list , Only this structure can add data to the map . We use it Map Common methods in class add、set_global_opts and render To configure the map .

 1c = (
2 Map(init_opts=opts.InitOpts(width="1000px", height="600px")) # Initialize map size
3 .set_global_opts(
4 title_opts=opts.TitleOpts(title="2019 Provinces in GDP Distribution map Company : One hundred million yuan "), # Configuration title
5 visualmap_opts=opts.VisualMapOpts(
6 type_ = "scatter" # Scatter type
7 )
8 )
9 .add("GDP",list,maptype="china") # take list Pass in , The map type is China map
10 .render("Map1.html")
11)

Run the above code , Open the generated... With a browser Map1.html, The effect is as follows :

picture

A friend may ask , There are maps , But your map is not easy to distinguish different provinces GDP Size . Don't panic , We continue to optimize the above code , Give basis to different provinces GDP The size of the configuration of different colors , Let you see at a glance .

 1c = (
2 Map(init_opts=opts.InitOpts(width="1000px", height="600px")) # Switchable themes
3 .set_global_opts(
4 title_opts=opts.TitleOpts(title="2019 Provinces in GDP Distribution map Company : One hundred million yuan "),
5 visualmap_opts=opts.VisualMapOpts(
6 min_=1000,
7 max_=110000,
8 range_text = ['GDP Total amount ( Billion ) Color range :', ''], # Between partitions
9 is_piecewise=True, # Define the legend as segmented , The default is continuous legend
10 pos_top= "middle", # Segment position
11 pos_left="left",
12 orient="vertical",
13 split_number=10 # Divide into 10 Intervals
14 )
15 )
16 .add("GDP",list,maptype="china")
17 .render("Map2.html")
18)

Run the above code , Open the generated... With a browser Map2.html, The effect is as follows :

What about? , Is the effect much better , The redder the color, the more GDP The higher the . Your province 2019 year GDP In which color segment ? Of course , For some friends with high aesthetic standards, they may still be unable to meet your requirements .

In that case , Then I will optimize the code , Add a theme to the map . Adding a theme is simple , as long as import Next ThemeType, Then add topics to Mpa() In the way . I take ThemeType.DARK For example, take a look at the effect .

1from pyecharts.globals import ThemeType # Introduce a theme
2Map(init_opts=opts.InitOpts(width="1000px", height="600px",theme = ThemeType.DARK)) # Add theme ThemeType.DARK

Run it to see the effect :

Is there any B Lattice rise n individual level The feeling of , If you're not satisfied ,ok,pyecharts Built in 10 You can switch between other topics . Radish and green vegetables are loved by each , Transfer yourself ~

Two 、Geo

Geo And Map similar , Can be set by maptype Parameter select map type , The supported methods are also similar to Map similar , I won't go into details here , Post code directly .

 1#Geo Map - Ripple diagram
2import pandas as pd
3from pyecharts import options as opts
4from pyecharts.charts import Geo
5from pyecharts.globals import ChartType
6
7data = pd.read_excel('GDP.xlsx')
8province = list(data["province"])
9gdp = list(data["2019_gdp"])
10list = [list(z) for z in zip(province,gdp)]
11print(list)
12c = (
13 Geo()
14 .add_schema(maptype="china")
15 .add(
16 "geo",
17 list, # Incoming data
18 symbol_size=10, large_threshold=110000, # Set the ripple size
19 type_=ChartType.EFFECT_SCATTER, # The map type is ripple map
20 )
21 .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
22 .set_global_opts(visualmap_opts=opts.VisualMapOpts(max_=110000),title_opts=opts.TitleOpts(title="2019 Provinces in GDP Ripple diagram "))
23 .render("Geomap1.html")
24)

Run it , The effect is as follows :

3、 ... and Bmap

Bmap It is an interface of Baidu map , If you Map and Geo I see ,Bmap It can be done in minutes . however , There is one caveat , You need to register on Baidu map open platform first , obtain AK Can be called . Registered address :https://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5 Register to obtain AK, You can make a map happily , Take the thermodynamic diagram as an example , The code is as follows .

 1#Bmap- Scatter plot 、 Heat map and ripple map
2import pandas as pd
3from pyecharts.charts import BMap
4from pyecharts import options as opts
5from pyecharts.globals import ChartType
6
7data = pd.read_excel('GDP.xlsx')
8province = list(data["province"])
9gdp = list(data["2019_gdp"])
10list = [list(z) for z in zip(province,gdp)]
11print(list)
12c = (
13 BMap(init_opts=opts.InitOpts(width="1000px", height="600px"))
14 .add_schema(baidu_ak=" Yours AK", center=[120.13066322374, 30.240018034923])
15 .add(
16 "GDP",
17 list,
18 type_="heatmap", #scatter Is a scatter plot ,heatmap Is the heat map ,ChartType.EFFECT_SCATTER Is a ripple diagram
19 label_opts=opts.LabelOpts(formatter="{b}")
20 )
21 .set_global_opts(
22 title_opts=opts.TitleOpts(title="2019 Provinces in GDP Heat map "), visualmap_opts=opts.VisualMapOpts(max_=110000)
23 )
24 .render("Bmap1.html")
25)

After operation , Long like this :

folium

Do you think the above maps can satisfy Charlie's pursuit of data visualization Aesthetics , Then you underestimate Charlie , I have studied , Find out folium The library is the existence of heaven .

First , I use python Got the Gaud map API Interface , It has won nearly... In Guangzhou 6000 Geographical data of scenic spots , Save as poi_scenic_spot.csv. The following are some data :

Then install folium library , Set stimulating battlefield base map , Of course, you can also change other base maps to play , The code provides mapbox Base map 、 Gaude base map, etc , You can switch at will .

 1#folium- Heat map
2import pandas as pd
3import folium
4from folium import plugins
5
6data = pd.read_csv('./poi_scenic_spot.csv',encoding='utf-8')
7
8# heatmap1 = folium.Map(location=[23.122373,113.268027], zoom_start=10,control_scale = True) # Make a map , Determine focus , Default underlay ( Slow loading )
9heatmap1 = folium.Map(location=[23.122373,113.268027], zoom_start=10,control_scale = True,tiles='stamen Terrain') # Stimulate the battlefield base map
10# heatmap1 = folium.Map(location=[23.122373,113.268027], zoom_start=10,control_scale = True,tiles='Mapbox Bright') #mapbox Base map
11# heatmap1 = folium.Map(location=[23.122373,113.268027], zoom_start=10,control_scale = True,tiles='stamentoner') # Black and white base map
12
13# heatmap1 = folium.Map( # Gaud base map
14# location=[23.122373,113.268027],
15# zoom_start=15,
16# control_scale = True,
17# tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
18# attr='&copy; <a href="http://ditu.amap.com/"> Gould map </a>'
19# )
20
21folium.Marker([23.122373,113.268027],popup='<i> Charlie </i>',icon=folium.Icon(icon='cloud',color='green')).add_to(heatmap1) # Create center marks
22heatmap1.add_child(plugins.HeatMap([[row["lat"],row["lon"]] for name, row in data.iterrows()])) # Incoming latitude and longitude
23heatmap1.save("folium_map1.html") # Generate web pages 

Can't wait to run , The effect is as follows :

Ha ha ha ha , What a big braised chicken .

The heat map is a bit of a hit , It is difficult for me to figure out the distribution of scenic spots in Guangzhou . Let's try a different picture .

 1#folium- Aggregate scatter map
2import pandas as pd
3import folium
4from folium import plugins
5
6data = pd.read_csv('./poi_scenic_spot.csv',encoding='utf-8')
7
8plotmap1 = folium.Map(location=[23.122373,113.268027], zoom_start=10,control_scale = True,tiles='stamentoner')
9
10folium.Marker([23.122373,113.268027],popup='<p > I am a J Brother </p>',icon=folium.Icon(icon='cloud',color='green')).add_to(plotmap1) # Create center marks
11plotmap1.add_child(plugins.MarkerCluster([[row["lat"],row["lon"]] for name, row in data.iterrows()]))
12plotmap1.save('folium_map2.html')

See the effect !

You say cool or not , Dazzle or not ?

junction language

Charlie thinks the above conclusion is complete , Of course ,python There are many more in our map library , It is worth further digging . I will also write the content of map visualization in the future , Welcome to continue to pay attention , Don't miss it ! Background replies from small partners interested in the data set and complete code used in this map “ Map visualization ” You can get it for free .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved