Pyecharts Drawing Maps (Geo and Map) (Rich details)
some time ago I participated in the US race, because considering some places to draw beautiful charts, in addition, according to the contents of previous years, it is found that the data of various countries need to be displayed through the world map, so I discovered that PyeCharts in Python python Library, this blog mainly shares the usage of GEO and MAP in Pyecharts. (The advantage of other blogs here may be that there are more details, right?)
1. Document URL: https://pyecharts.org/zh-cn/intro
Directly apply code
1. Since the default output type of PyeCharts is HTML file displayed on the webpage, if you copy the picture or screenshot directly on the webpage, the clarity will be very poor. If you want to save it directly as a PNG picture
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot # This influence of the final output picture
2. Import related MAP packages
from pyecharts.charts import Map # Import map module
from pyecharts import options as opts
3. Map display settings
Among them, the data_pair in .add is the form of the tuple list. It can be built by itself according to the situation. ]
worldmap=Map(init_opts=opts.InitOpts(width="800px",height="400px",bg_color='white'))
# Initialize the map size and background color
worldmap.add(" ",data_pair=datapairtwo,maptype="world",is_map_symbol_show=False)
# type is the world map, IS_MAP_SYMBOL_SHOW can choose whether to display the red punctuation of the world maps on the world map
worldmap.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
# Set is_show = false, so that the name of each country on the world map will not be displayed on the map
worldmap.set_global_opts(title_opts=opts.TitleOpts(title=" "),legend_opts=opts.LegendOpts(is_show=False),
visualmap_opts=opts.VisualMapOpts(min_=0,max_=20,orient="horizontal",type_ ="color",
range_color=['#FCFCFC','#5CACEE','#6495ED'],
pos_left=360,pos_bottom=60,item_width=15,item_height=80))
# The title is set as a space, that is, the title is not displayed, the legend is set to not display, the visual mapping range is 0 ~ 20, placed to be placed horizontally, the visual mapping uses color changes as a transition. Range_color is the color change range. The position and height width of the visual mapping. Here is mainly to throw turning to the jade. If you still want to set up other, you can add it according to the official manual
#WORLDMAP.Render ("name.html") #webpage form output
make_snapshot(snapshot,worldmap.render(),"worldfair.png")# Image output
4. In order to feel the impact of the parameter settings intuitively, I will show it through the output of the two sets of code
code 1:
# Drawing code
from pyecharts.charts import Map # Import map module
from pyecharts import options as opts
def get_regionname_data(txtadressname):
alldata=[]
with open(txtadressname, 'r', encoding='UTF-8') as f:
lines = f.readlines()# Will automatically processes the file according to the changing symbols to form a list of each line that will be processed.
for line in lines[1:]: # The first 1 line is the head, removed, this is according to the actual situation
line_info = line.strip() # Delete the empty character of the first and tail of each line string
alldata.append(line_info)
return alldata
def get_number_data(txtadressname):
alldata=[]
with open(txtadressname, 'r', encoding='UTF-8') as f:
lines = f.readlines()# will automatically processes the file according to the changing symbols that will be processed to form a list to return
for line in lines[1:]: # The first 1 line is the head, removed, this is according to the actual situation
linshidata=[]
line_info = line.strip().split() # separate the characters in a line into a list, delete the empty lattice
linshidata=[line_info[0],line_info[1]]
alldata.append(linshidata)
return alldata
regionadress="C:\\Users\\86151\\Desktop\\pythonadress.txt"
dataadderss="C:\\Users\\86151\\Desktop\\pythonhuahua.txt"
regionname=get_regionname_data(regionadress)
data=get_number_data(dataadderss)
a_listone=[]
a_listtwo=[]
datapairone=[]
datapairtwo=[]
long=len(regionname)
for i in range(0,long):
a_listone=[regionname[i],data[i][0]]
a=tuple(a_listone)
datapairone.append(a)
a_listtwo = [regionname[i],data[i][1]]
b=tuple(a_listtwo)
datapairtwo.append(b)
# The above part is to generate the list list, you can refer to
worldmap=Map(init_opts=opts.InitOpts(width="800px",height="400px",bg_color='white'))
worldmap.add(" ",data_pair=datapairtwo,maptype="world",is_map_symbol_show=True)
worldmap.set_series_opts(label_opts=opts.LabelOpts(is_show=True))
worldmap.set_global_opts(title_opts=opts.TitleOpts(title="This is the title"),legend_opts=opts.LegendOpts(is_show=True),
visualmap_opts=opts.VisualMapOpts(min_=0,max_=20,orient="horizontal",type_ ="color",
range_color=['#FCFCFC','#5CACEE','#6495ED'],
pos_left=360,pos_bottom=60,item_width=15,item_height=80))
worldmap.render()
My txt file format is
Output 1:
code 2:
from pyecharts.charts import Map # Import map module
from pyecharts import options as opts
#DataPair data acquisition is consistent with code 1
worldmap=Map(init_opts=opts.InitOpts(width="800px",height="400px",bg_color='white'))
worldmap.add(" ",data_pair=datapairtwo,maptype="world",is_map_symbol_show=False)
# Cancel red dot display
worldmap.set_series_opts(label_opts=opts.LabelOpts(is_show=False))# Cancel the national name display
worldmap.set_global_opts(title_opts=opts.TitleOpts(title=" "),legend_opts=opts.LegendOpts(is_show=False),# Cancel the title display and legend display
visualmap_opts=opts.VisualMapOpts(min_=0,max_=20,orient="horizontal",type_ ="color",
range_color=['#FCFCFC','#5CACEE','#6495ED'],
pos_left=360,pos_bottom=60,item_width=15,item_height=80))
worldmap.render()
Output 2:
You can see that the whole picture is a lot refreshing instantly
Direct code
# Import output picture tool
from pyecharts.charts import Geo
from pyecharts import options as opts
from pyecharts.globals import GeoType
from pyecharts.globals import ChartType, SymbolType
def get_geo_data(txtname):
alldata=[]
with open(txtname, 'r', encoding='UTF-8') as f:
lines = f.readlines()# Will automatically processes the file according to the changing symbols to form a list of each line that is processed and returns a list
for line in lines[1:]: # The first 1 line is the head, removed, this is according to the actual situation
latlon=[]
line_info = line.strip().split() # separate the characters in a line into a list, delete the empty lattice
latlon=[line_info[0],float(line_info[1]),float(line_info[2])]
# Call the site, merge the latitude and latitude coordinates into a list
alldata.append(latlon)
return alldata# finally form a nested list
# List of coordinate data
zuobiao=get_geo_data("D: \# Training third model \ pythoncode_document \ latlon.txt")
special_spot=[7911, 7956, 7943, 7958, 7938, 8004, 8042, 8159, 8157, 8122, 8063, 7995, 8039, 8016, 7846, 7838, 7818, 7786, 7748, 7756, 7622, 7620, 7597, 7568, 7603, 7607, 7647, 7626, 7629, 7588, 7410, 7243, 7171, 7016, 6895, 6723]
# 5 5 5 5 (first build a list before constructing the cost group)
jiantoulist=[]
lujinglist=[]
a_list=[]
datapair=[]
for i in special_spot:
lujinglist.append(zuobiao[i][0])
a_list=[zuobiao[i][0],20]
a=tuple(a_list)
datapair.append(a)
linshilist=[]
for i in range(0,len(lujinglist)-1):
linshilist=[lujinglist[i],lujinglist[i+1]]
b=tuple(linshilist)
jiantoulist.append(b)
# Construction of the list list successfully
geo = Geo(init_opts=opts.InitOpts(width="600px",height="400px",bg_color="white"))
geo.add_schema(maptype="Hangzhou",center=[120.2779620000,30.3148070000],itemstyle_opts=opts.ItemStyleOpts(color="white", border_color="#111"))
#Center represents the center point of this picture, itemStyle_opts is used to set the map style, and the color is set here
for i in special_spot:
geo.add_coordinate(name=zuobiao[i][0],longitude=zuobiao[i][2],latitude=zuobiao[i][1])
# Add new coordinate points. An important difference between geo map GEO and map map is that GEO can add new coordinate points to the map
geo.add('',datapair, type_=GeoType.EFFECT_SCATTER, symbol_size=1,color="blue")
geo.add(
"geo",
data_pair=jiantoulist,
type_=ChartType.LINES, # This refers to the line type
effect_opts=opts.EffectOpts(symbol=SymbolType.ARROW,symbol_size=5,color="yellow"),
# Set the style of the line
linestyle_opts=opts.LineStyleOpts(curve=0.2),# Set the curvature of the line
is_large=True,
is_polyline=False, # is used to set the style settings between the locations on the map,
)
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=True,font_size=10,position="top"))
geo.set_global_opts(title_opts=opts.TitleOpts(title="Hangzhou"))
geo.render()
#make_snapshot(snapshot,geo.render(), "tupain.png")
My TXT data latitude and longitude format:
Output picture:
You can see that because the added coordinates are concentrated in a small area in Hangzhou, the overall show of the map is very large. So how to enlarge the map to clearly see which part of the coordinate point?
Change code
geo.add_schema(maptype="Hangzhou",center=[120.2779620000,30.3148070000],itemstyle_opts=opts.ItemStyleOpts(color="white", border_color="#111"))
replace
geo.add_schema(maptype="Hangzhou",center=[120.2779620000,30.3148070000],zoom=20,itemstyle_opts=opts.ItemStyleOpts(color="white", border_color="#111"))
Output:
zoom adjustmentMake you clearly see the marking point and the connected segment, but we found another problem. The label in the figure should besite name, but the picture shows the latitude and longitude of the siteAs a label, how to mark it as a site name?
Change code
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=True,font_size=10,position="top"))
Change to
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=True,formatter='{b}',font_size=10,position="top"))
Output:
At this time, the correct place name can be displayed. For specific reasons, you can check the usage of the manual Formatter. But at this time found in the pictureplace name is too big, andRed Arrowis also very big, making it very unsightly, how to solve it?
1. Make the label not displayed as Label Settingsis_show=Flase
2. In the codeis_polyline=False, modified to true
result is:
Finally complete code:
from pyecharts.charts import Geo
from pyecharts import options as opts
from pyecharts.globals import GeoType
from pyecharts.globals import ChartType, SymbolType
# 9 9 9 9 is consistent with the previous code
geo = Geo(init_opts=opts.InitOpts(width="600px",height="400px",bg_color="white"))
geo.add_schema(maptype="Hangzhou",center=[120.2779620000,30.3148070000],zoom=20,itemstyle_opts=opts.ItemStyleOpts(color="white", border_color="#111"),)
for i in special_spot:
geo.add_coordinate(name=zuobiao[i][0],longitude=zuobiao[i][2],latitude=zuobiao[i][1])
geo.add('',datapair, type_=GeoType.EFFECT_SCATTER, symbol_size=1,color="blue")
geo.add(
"geo",
data_pair=jiantoulist,
type_=ChartType.LINES,
effect_opts=opts.EffectOpts(symbol=SymbolType.ARROW,symbol_size=5,color="yellow"),
linestyle_opts=opts.LineStyleOpts(curve=0.2),
is_large=True,
is_polyline=True,
)
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False,formatter='{b}',font_size=10,position="top"))
geo.set_global_opts(title_opts=opts.TitleOpts(title="Hangzhou"))
geo.render()
The above is what I shared with you about how Map and GEO add data when using, how to optimize the graphics to share, Pyecharts also has a lot of drawing functions. You can learn by checking the manual.
1.Various colors Hexades 16 -entry codes
2.MAP Chinese and English Correspondence Table
3.Answer to Formatter
4.PyeCharts How to output it to PNG format