SoFunction
Updated on 2024-11-10

Example of pyecharts dynamic trajectory chart implementation

Today's topic! Recently, many friends asked about pyecharts, especially the production of geographic coordinate charts, they said they were attracted by the beauty of its graphics. It just so happens that a colleague also asked up today, so today we will take the dynamic geographic trajectory chart of pyecharts as an example, and say how to use pyecharts.

import pandas as pd   
import random
from pyecharts import GeoLines, Style  #The class of a geographic track map isGeolines

In the colleague took a part of the domestic city latitude and longitude data, first read the data with pandas to see what the data looks like, we found that the data consists of a column, the basic structure of the 'place name': ['longitude', 'latitude'], then the next we will be the name of the place, longitude, latitude extracted.

#Read the data
data = pd.read_excel('./Desktop/',header = None,names = ['name'])
print(())
        name
0   'Shanghai': [121.4648,31.2891],
1    'Dongguan': [113.8953,22.901],
2   'Dongying': [118.7073,37.5513],
3    'Zhongshan': [113.4229,22.478],
4   'Linfen': [111.4783,36.1615],
 
# Write an iteration that extracts the place names, longitude and latitude of each place and accesses them in a DataFrame.
city_list = []
lad_list = []
long_list = []
for i in data['name']:
  s = ().split(':')     # Remove leading and trailing spaces and split characters with ":" as separator
  city = s[0][1:-1]        # Take the first character of the split to get the place name
  lad = s[1].split(',')[0][2:]   # Take the second character of the split and continue to split characters with ',' as separator
  long = s[1].split(',')[1][:-2]
  city_list.append(city)
  lad_list.append(lad)
  long_list.append(long)
result = ({'Location': city_list, 'Longitude': lad_list, 'Latitude': long_list})

From the RESULT data frame we see that a total of 114 rows, 3 columns of data, 114 rows is too much to draw to the map will be very messy, so we use random packets to randomly sample 20 out to do the experiment;

Before sampling, we need to organize the data into the format required by geolines, in the format [('start point','end point')];

In addition, because we want to customize the latitude and longitude of each city (worried about some cities in the map does not show up), pyecharts city latitude and longitude of the format of {'city': ['longitude', 'latitude']}, so we also need to assemble our data.

# Organize data with Dongguan as the starting point and each other city as the end point
plotting = result[result['Location'] != 'Dongguan']['Location'].apply(lambda x : ('Dongguan',x))
 
#Customize the latitude and longitude of each city
geo_cities_coords = {[i]['Location']:[[i]['Longitude'],[i]['Latitude']] for i in range(len(result))}
 
# Random sample of 20 city portfolios
plotting_data = (list(plotting),20)

The data is ready, the next set comes, first set the format of the canvas, then the geolines as instances of the class Geolines, then set the parameters of the geolines, and finally show the results!

# Set the format of the canvas
style = Style(title_pos="center", 
       width=1000, 
       height=800)
 
# Format of partial geo-trajectory maps
style_geolines = (is_label_show=True,
           line_curve=0.3,       # Curvature of the trajectory line, 0-1
           line_opacity=0.6,      # Transparency of the trace line, 0-1
           geo_effect_symbol='plane', #Special effects graphics, circle, plane, pin and so on.
           geo_effect_symbolsize=10,  #The size of the effects graphic
           geo_effect_color='#7FFFD4', #color of the effect
           geo_effect_traillength=0.1, Trailing effect of #FX graphics, 0-1
           label_color=['#FFA500', '#FFF68F'], # the color of the trajectory line, the color of the label point, the
           border_color='#97FFFF', #Color of the border
           geo_normal_color='#36648B', #color of the map
           label_formatter='{b}',   # tag format
           legend_pos = 'left')
 
#Mapping
geolines = GeoLines('Little Man's pyechart travel track map', **style.init_style)
('From Dongguan',
       plotting_data,
       maptype='china',  #The type of map can be a provincial place, such as 'Guangdong', or a city, such as 'Dongguan' and so on.
       geo_cities_coords=geo_cities_coords,
       **style_geolines)
 
#publish, get html file for graphics
()

Do here geographic track map has been completed, then if we want to draw a both departure and return track map how to draw? In fact, it is very simple, on the basis of the above, and then add an add can be, as follows:

('Back to Dongguan',
       [('Haikou','Dongguan'),('Lhasa','Dongguan'),('Guizhou','Dongguan'),('Lanzhou','Dongguan')],
       maptype='china', 
       geo_cities_coords=geo_cities_coords,
       **style_geolines)

Well, we saw a few small planes back to Dongguan, respectively, we set up Lhasa, Guizhou, Haikou and Lanzhou, so it seems a bit chaotic, then we can set a parameter that makes the departure and return trip separately, first set up is_legend_show = True, then set legend_selectdmode = 'single', and click on the different legends to display them as follows:

style_geolines = (is_label_show=True,
           line_curve=0.3,       
           line_opacity=0.6,      
           geo_effect_symbol='plane', 
           geo_effect_symbolsize=10,  
           geo_effect_color='#7FFFD4',
           geo_effect_traillength=0.1,
           label_color=['#FFA500', '#FFF68F'],
           border_color='#97FFFF', 
           geo_normal_color='#36648B', 
           label_formatter="{b}", 
           is_legend_show=True,
           legend_pos = 'left',
           legend_selectdmode = 'single')  #Single instance pattern
('From Dongguan',     # Legend 1 Name
       plotting_data,
       maptype='china',  
       geo_cities_coords=geo_cities_coords,
       **style_geolines)
('Back to Dongguan',      # Legend 2 Name
       [('Haikou','Dongguan'),('Lhasa','Dongguan'),('Guizhou','Dongguan'),('Lanzhou','Dongguan')],
       maptype='china', 
       geo_cities_coords=geo_cities_coords,
       **style_geolines)

to this article on the realization of pyecharts dynamic trajectory chart example of the article is introduced to this, more related pyecharts dynamic trajectory chart content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!