First, Pyecharts
Pyecharts is a library for generating Echarts diagrams
Echarts is an open source DATA visualization JS library, mainly used for data visualization, Pyecharts is a class library for generating Echarts charts. This is essentially Echarts docking with Python
Pyecharts can be used to generate standalone web pages, or integrated in Flask, Django
PIP install Pyecharts ==1.5
Pyecharts chart preparation
1. Global configuration items
Global configuration items can be set using the set_global_options method
The configuration is as follows:
2. Series configuration items
This can be set using the set_series_options method
This parameter is used to configure the specific parameters of font, color, and line lamp
3. Note: Data format
What Pyecharts is essentially doing is serializing Echarts configuration items into JSON format from the Python Dict, so what format of data types Pyecharts supports depends on what data types JSON supports
Pyecharts is a generic third party library, and it is impossible to care about all of the developers’ usage scenarios. This transformation requires us to introduce two third party libraries, numPY/Pandas, which are too important, so we leave it to the developers
Specific conversion mode:
You can use series.tolist () for quick conversions
4. More configurations
For more information about the configuration, see pyecharts.org/#/zh-cn/
Color comparison table lesson reference: www.fynas.com/system-draw…
3. Bar chart
Take the quantity of various goods sold by merchant A and merchant B as an example to draw A bar chart
shirt | sweater | tie | The trousers | Dust coat | High heels | socks | |
---|---|---|---|---|---|---|---|
Businesses A | 114 | 55 | 27 | 101 | 125 | 27 | 105 |
Business B | 57 | 134 | 137 | 129 | 145 | 60 | 49 |
Code implementation:
from pyecharts import options as opts # Config module
from pyecharts.charts import Bar
Instantiate the bar object
bar = Bar()
# 2. Add data
# Horizontal data
bar.add_xaxis(
xaxis_data=['shirt'.'sweaters'.'tie'.'pants'.'trench coat'.'High heels'.'socks'])Add vertical axis data
bar.add_yaxis(
series_name=Merchants' A '.# Column name
yaxis_data=[114.55.27.101.125.27.105].# Merchant A's data
)
Add vertical axis data
bar.add_yaxis(
series_name=Merchants' B '.# Column name
yaxis_data=[57.134.137.129.145.60.49].# Merchant A's data
)
# 3. Global configuration items
bar.set_global_opts(
# set the title
title_opts=opts.TitleOpts(
title='Bar test'))# 4. Series configuration items
bar.set_series_opts(
# set the tag
label_opts=opts.LabelOpts(
is_show=True,
position='right'.# tag position))# Set direction
bar.reversal_axis()
# 5. Generate files
bar.render('./ bar graph.html ')
Copy the code
Fourth, the pie chart
The pie chart is drawn based on the statistics of Python system classes in each branch school
Statistics on the number of branch schools in each region
Region, | Number of Classes in the Python system |
---|---|
Beijing | 130 |
henan | 65 |
Guangzhou | 60 |
wuhan | 23 |
chengdu | 30 |
hangzhou | 33 |
Code implementation:
# guide package
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.globals import ThemeType # Theme module
import pandas as pd
Instantiate the object
pie = Pie(
Initial configuration
init_opts=opts.InitOpts(
width='1200px'.# canvas width
height='500px'.# Canvas height
# theme='white', # theme, set mode
theme=ThemeType.WHITE, # Theme, set mode
page_title='Pie chart of Python branch schools'.# bg_color='#F0F8FF', # background color))Load branch data
data = pd.read_excel('./ Number of Python branch schools. XLSX ')
print('data:\n', data)
# for TMP in zip (data. Loc [: ', ']. Tolist (), and data. The loc [: 'number']. Tolist ()) :
# print(tmp)
data_pair = [(k, v) for k, v in zip(data.loc[:, '分校'].tolist(), data.loc[:, 'number'].tolist())]
print('data_pair:\n', data_pair)
# 2. Add data
pie.add(
series_name=data.loc[:, '分校'].tolist(), # legend name
data_pair=data_pair, # Data format: [(k1,v1),(k2,v2)... .
radius=['30%'.'70%'].# Radius, the first is the inside diameter, the second is the outside diameter, usually set to a percentage
is_clockwise=True.Arrange clockwise
)
# 3. Set global configuration items
pie.set_global_opts(
# set the title
title_opts=opts.TitleOpts(
title='Pie chart of Python branch schools'.# Title name
subtitle='Python0421 class of Guangzhou Branch'.# subtitle
pos_left='left'.# position
),
# Set legend
legend_opts=opts.LegendOpts(
is_show=True.# Show the legend
pos_left='center'.# Position -- center))# 4. Set the series of configuration items
pie.set_series_opts(
# set the tag
label_opts=opts.LabelOpts(
is_show=True.# Show tags
font_size=12.# font size
font_style='italic'.# font style, slant
formatter='{b}:{d}%'.# Display style {a} series name {b} Data item name {C} Value {d} percentage))# 5. Generate files
pie.render('./ Pie chart of proportion of people in Python campuses. HTML ')
Copy the code
Five, line chart
COVID-19 (Corona Virus Disease 2019, COVID-19 for short) stands for pneumonia caused by 2019-Novel coronavirus infection. Since December 2019, A number of pneumonia cases of unknown cause with a history of exposure to seafood markets in South China have been detected in some hospitals in Wuhan, Hubei Province, which have been confirmed as acute respiratory infections caused by 2019 Novel Coronavirus infection
To this end, the Hubei government, provinces and even the country have attached great importance to the development of the novel coronavirus outbreak, and have taken prompt measures to isolate and treat those who are sick
In this case, statistical analysis of epidemic data was conducted with the help of national release data (part)
A broken line chart and a bar chart are drawn based on the national epidemic statistics as of 10:49 p.m. on February 6, 2020
Statistics of daily changes in China’s epidemic data
city | time | deaths | Number of cure | Number of suspected | provinces | Confirmed the number |
---|---|---|---|---|---|---|
The national | 2020-02-06 | 564 | 1180 | 24702 | The national | 28060 |
The national | 2020-02-05 | 564 | 1153 | 24702 | The national | 28060 |
The national | 2020-02-04 | 491 | 892 | 23260 | The national | 24363 |
The national | 2020-02-03 | 425 | 630 | 23214 | The national | 20471 |
The national | 2020-02-02 | 361 | 475 | 21558 | The national | 17238 |
The national | 2020-02-01 | 304 | 328 | 19544 | The national | 14411 |
The national | 2020-01-31 | 259 | 243 | 17988 | The national | 11821 |
The national | 2020-01-30 | 213 | 171 | 15238 | The national | 9720 |
The national | 2020-01-29 | 170 | 124 | 12167 | The national | 7736 |
The national | 2020-01-28 | 132 | 103 | 9239 | The national | 5997 |
The national | 2020-01-27 | 106 | 51 | 6973 | The national | 4535 |
The national | 2020-01-26 | 80 | 49 | 5794 | The national | 2761 |
The national | 2020-01-25 | 56 | 38 | 2684 | The national | 1985 |
The national | 2020-01-24 | 41 | 38 | 1965 | The national | 1297 |
The national | 2020-01-23 | 25 | 34 | 1072 | The national | 830 |
Code implementation:
# Drawing module
from pyecharts.charts import *
# Config module
from pyecharts import options as opts
# Theme module
from pyecharts.globals import ThemeType
import pandas as pd
Instantiate the object
bar = Bar(
# init_opts=opts.InitOpts(
# width='2000px',
# # height='700px'
#)
)
# load data
history_data = pd.read_excel('./ Epidemic history data.xls', index_col=0)
print('history_data:\n', history_data)
Get horizontal axis data
# (1) Get the time data and change its type to STR
x_data = history_data.loc[:, 'time'].astype('str')
# PI (2) the other way around
x_data = x_data[::-1].tolist()
print('x_data:\n', x_data)
Prepare the vertical axis data
# Death data
death_data = history_data.loc[:, 'Deaths'] [: : -1].tolist()
print('death_data:\n', death_data)
# Confirmed data
ensure_data = history_data.loc[:, 'Confirmed number'] [: : -1].tolist()
print('ensure_data:\n', ensure_data)
# Suspected data
suspected_data = history_data.loc[:, 'Suspected number'] [: : -1].tolist()
print('suspected_data:\n', suspected_data)
# Cure data
cure_data = history_data.loc[:, 'Cure number'] [: : -1].tolist()
print('cure_data:\n', cure_data)
# 2. Add data
# Horizontal data
bar.add_xaxis(
xaxis_data=x_data, # Horizontal data
)
# Vertical axis data
bar.add_yaxis(
series_name='Deaths'.# legend name
yaxis_data=death_data, # data
yaxis_index=1.# For multiple vertical axes, select the first vertical axis as the number of deaths reference
)
bar.add_yaxis(
series_name='Cure number'.# legend name
yaxis_data=cure_data, # data
yaxis_index=2.# when multiple vertical axes are represented, the second vertical axis is selected as the reference for healing number
)
# Increase the vertical axis
bar.extend_axis(
Add a vertical axis
yaxis=opts.AxisOpts(
type_='value'.Type of coordinate axes
name='Deaths'.The name of the coordinate axis
min_=0.# the minimum
max_=1200.# maximum value,
position='right'.# Position, right
offset=0.# Coordinate line setup
axisline_opts=opts.AxisLineOpts(
is_show=True.# display coordinate line,
# Coordinate line style
linestyle_opts=opts.LineStyleOpts(
color='#a5a391'.# Color of the line)),# coordinate line label Settings
axislabel_opts=opts.LabelOpts(
is_show=True.Display axis label
position='top'.# tag position
formatter='{value}' # label value
)
)
)
bar.extend_axis(
Add a vertical axis
yaxis=opts.AxisOpts(
type_='value'.Type of coordinate axes
name='Cure number'.The name of the coordinate axis
min_=0.# the minimum
max_=1200.# maximum value,
position='right'.# Position, right
offset=60.# Coordinate line setup
axisline_opts=opts.AxisLineOpts(
is_show=True.# display coordinate line,
# Coordinate line style
linestyle_opts=opts.LineStyleOpts(
color='#fd5956'.# Color of the line)),# coordinate line label Settings
axislabel_opts=opts.LabelOpts(
is_show=True.Display axis label
position='top'.# tag position
formatter='{value}' # label value
)
)
)
bar.extend_axis(
Add a vertical axis
yaxis=opts.AxisOpts(
type_='value'.Type of coordinate axes
name='Suspected number'.The name of the coordinate axis
min_=0.# the minimum
max_=30000.# maximum value,
position='right'.# Position, right
offset=120.# Coordinate line setup
axisline_opts=opts.AxisLineOpts(
is_show=True.# display coordinate line,
# Coordinate line style
linestyle_opts=opts.LineStyleOpts(
color='#ac7e04'.# Color of the line)),# coordinate line label Settings
axislabel_opts=opts.LabelOpts(
is_show=True.Display axis label
position='top'.# tag position
formatter='{value}' # label value)))# Draw a line chart
Instantiate the object
line = Line()
# add data
Add horizontal axis data
line.add_xaxis(
xaxis_data=x_data
)
Add vertical axis data
line.add_yaxis(
series_name='Confirmed number'.# legend name
y_axis=ensure_data, # Confirmed data
yaxis_index=0.# select the 0 axis as a reference
# tag Settings
label_opts=opts.LabelOpts(
is_show=False
)
)
line.add_yaxis(
series_name='Suspected number',
y_axis=suspected_data, # Suspected data
yaxis_index=3.# tag Settings
label_opts=opts.LabelOpts(
is_show=False),# 3. Global configuration
bar.set_global_opts(
# header configuration
title_opts=opts.TitleOpts(
title='Epidemic Trends in China'.# titles
subtitle='Python0421 class of Guangzhou Branch'.# subtitle
pos_left='3%'.# the position of the title
pos_top='5%'.# the position of the title
# Set the main heading style
title_textstyle_opts=opts.TextStyleOpts(
# color='#000000', # text color
font_style='normal'.# font style
# font_size=12, # font size
font_weight='normal'.The size of the # font
),
# Subtitle style Settings
subtitle_textstyle_opts=opts.TextStyleOpts(
# color='#000000', # text color
font_style='normal'.# font style
# font_size=7, # font size
font_weight='normal'.The size of the # font)),# legend setup
legend_opts=opts.LegendOpts(
is_show=True.# display legend
pos_left='25%'.# legend position
pos_top='7%'.# legend position
# Legend Style Settings - Do not set them yet
# textstyle_opts=opts.TextStyleOpts()
),
# Vertical axis Settings
yaxis_opts=opts.AxisOpts(
type_='value'.Type of coordinate axes
name='Confirmed number'.The name of the coordinate axis
min_=0.# the minimum
max_=30000.# maximum value,
position='left'.# Position, left
# Coordinate line setup
axisline_opts=opts.AxisLineOpts(
is_show=True.# display coordinate line,
# Coordinate line style
linestyle_opts=opts.LineStyleOpts(
color='#FFF5EE'.# Color of the line)),# coordinate line label Settings
axislabel_opts=opts.LabelOpts(
is_show=True.Display axis label
position='top',
formatter='{value}')),# Prompt box Settings
tooltip_opts=opts.TooltipOpts(
trigger='axis'.# 'axis': Axis trigger, mainly used in bar charts, line charts, etc., which use category axes
axis_pointer_type='cross'.# 'cross' : Crosshair indicator. This is a shorthand for enabling axisPointer for two orthogonal axes.
),
# Text box Settings
graphic_opts=opts.GraphicGroup(
# Configuration items for graphics
# Position of text relative to graph
graphic_item=opts.GraphicItem(
# Control the overall position
left="75%",
top="45%",
),
children=[
# # opts.GraphicRect controls the display of the box
# # If you don't need the box, remove the paragraph
# opts.GraphicRect(
# # Text box position
# graphic_item=opts.GraphicItem(
# z=100, the display position of the # z axis
# left="center", # left
# top="middle", # bottom position
#).
# # textbox shape
# graphic_shape_opts=opts.GraphicShapeOpts(
# width=420, # width
# height=180, # height
#).
# # text box style
# graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
# fill="# FFF ", # text box fill color
# stroke="#00008B", # border color
# line_width=10, # border width
# shadow_blur=8, # shadow correlation
# shadow_offset_x=3
# shadow_offset_y=3
# shadow_color="rgba(0,0,0,0.3)", # shadow color
#).
#).
# config text
opts.GraphicText(
Position of text --> Position of text relative to text box
graphic_item=opts.GraphicItem(
left="center",
top='middle',
z=100.# display position
scale=[1.5.1.5].# scaling
),
graphic_textstyle_opts=opts.GraphicTextStyleOpts(
# Text message
text="Up to {},\n the relevant information of the COVID-19 virus across the country is :\n death cases are {} cases,\n cured cases are {} cases,\ N confirmed cases are {} cases,\n suspected cases are {} cases,\n experts call for :\n the majority of the national policy allocation for epidemic prevention.".format(
history_data.loc[0.'time'], history_data.loc[0.'Deaths'], history_data.loc[0.'Cure number'],
history_data.loc[0.'Confirmed number'], history_data.loc[0.'Suspected number']
),
font="13px Microsoft YaHei".# font and font size
text_align='left'.Align horizontally to the left
text_vertical_align='middle'.# Vertical alignment: Default None,
Color and width of the # font
graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
fill='#ffdf22'.# color
line_width=1.2.# width)))]))# 4. Add a series of configuration items
bar.set_series_opts(
# tag Settings
label_opts=opts.LabelOpts(
is_show=True.# Show tags
position='top'.# tag position),# Stack multiple graphics
all_chart = bar.overlap(line)
# combination
grid = Grid(
Initial configuration
init_opts=opts.InitOpts(
width="1750px".# width
height='650px'.# height
theme=ThemeType.PURPLE_PASSION, Topic #))# add chart
grid.add(
# add chart
chart=all_chart,
# Set the combined configuration
grid_opts=opts.GridOpts(pos_top="20%".# position
pos_left="5%".# position
pos_right="40%" # position
),
is_control_axis_index=True.# control index
)
# 5. Generate files
grid.render('./ combination of bar chart and line chart. HTML ')
Copy the code
6. Map making
(1) Take the maps of popular migration routes before wuhan was closed down (0120, 0121, 0122) as examples to draw provincial maps
Before the lockdown of Wuhan, people migrated to the city
time | city |
---|---|
2020-01-20 | Into Wuhan Xiaogan, Huanggang, Ezhou, Jingzhou, Huangshi, Xiangyang |
2020-01-20 | Wuhan xiaogan, Huanggang, Jingzhou, Xiangyang, Huangshi, Jingmen, Ezhou, Suizhou, Xiantao |
2020-01-21 | Into Wuhan Xiaogan, Huanggang, Jingzhou, Ezhou, Huangshi |
2020-01-22 | Into Wuhan Xiaogan, Huanggang, Ezhou, Jingzhou, Xianning, Yellowstone |
2020-01-22 | Out of Wuhan Xiaogan, Huanggang, Jingzhou, Xiangyang, Jingzhou, Suizhou, Yichang, Yellowstone, Ezhou |
Code implementation:
# Import flow map
from pyecharts.charts import Geo
# Theme module
from pyecharts.globals import ThemeType
# Config module
from pyecharts import options as opts
#
from pyecharts.globals import GeoType
Instantiate the object
geo = Geo(
Initial configuration
init_opts=opts.InitOpts(
width='900px',
height='500px',
theme=ThemeType.CHALK, Topic #
page_title='Flow map'.# page name))# 2. Add a map type
geo.add_schema(
maptype='hubei'.# Map type, China map is China, Guangdong map is Guangdong, world map is World
# Change the map style
itemstyle_opts=opts.ItemStyleOpts(
# Map color
color='#FF8C00'.# Map edge color
border_color='#ffdf22',
area_color='#FF8C00'))# Build the access data of Wuhan before lockdown (data within Hubei Province)
# out -- represents wuhan --> the city
# enter -- represents the city --> Wuhan
data_0120_ru = 'Xiaogan, Huanggang, Ezhou, Jingzhou, Huangshi, Xiangyang'
data_0120_chu = 'Xiaogan, Huanggang, Jingzhou, Xiangyang, Huangshi, Jingmen, Ezhou, Suizhou, Xiantao'
data_0121_ru = 'Xiaogan, Huanggang, Jingzhou, Ezhou, Huangshi'
data_0121_chu = 'Xiaogan, Huanggang, Jingzhou, Xiangyang, Jingmen, Huangshi, Suizhou, Ezhou, Xiantao'
data_0122_ru = 'Xiaogan, Huanggang, Ezhou, Jingzhou, Xianning, Huangshi'
data_0122_chu = Xiaogan, Huanggang, Jingzhou, Xiangyang, Jingzhou, Suizhou, Yichang, Huangshi, Ezhou
# data_pair can be exactly [(out, in),(out, in),...
# [(Xiaogan, Wuhan),(Huanggang, Wuhan),(Wuhan, Huangshi),...]
Build a List to store the data into Wuhan
data_ru = []
# building data_pair
for city_str in [data_0120_ru, data_0121_ru, data_0122_ru]:
# city_str: city string of Wuhan
# split
city_list = city_str.split(', ')
# print('city_list:\n', city_list)
Add city_list to data_ru
data_ru.extend(city_list)
Decrement data_ru
data_ru = list(set(data_ru))
# building data_pair_ru
data_pair_ru = [(city, 'wuhan') for city in data_ru]
Build a List to store wuhan data
data_chu = []
# Build wuhan data
for city_str in [data_0120_chu, data_0121_chu, data_0122_chu]:
# city_str: string of the city out of Wuhan
# split
city_list = city_str.split("、")
Add # city_list to data_chu
data_chu.extend(city_list)
Delete data_chu
data_chu = list(set(data_chu))
# building data_pair_chu
data_pair_chu = [('wuhan', city) for city in data_chu]
# print('data_pair_ru:\n', data_pair_ru)
# print('data_pair_chu:\n', data_pair_chu)
# Combine the data out of Wuhan and the data into Wuhan
data_pair = data_pair_ru + data_pair_chu
print('data_pair:\n', data_pair)
# 3. Add data
geo.add(
series_name=' '.# Set to null
data_pair=data_pair, # data
type_=GeoType.LINES, # linear
# Ripple effect Settings
effect_opts=opts.EffectOpts(
# Ripple draw style
brush_type='stroke'.# Type of effect point
symbol='arrow',
symbol_size=5,
color='yellow'
),
# Line style
linestyle_opts=opts.LineStyleOpts(
# Degree of bending
curve=0.2.# Line style
type_='solid',
color='#7FFF00'))# 4. Global configuration items
geo.set_global_opts(
# header configuration
title_opts=opts.TitleOpts(
title='Map of The Flow of Wuhan before lockdown',
pos_left='center'
),
legend_opts=opts.LegendOpts(
is_show=False
),
# Text box Settings
graphic_opts=opts.GraphicGroup(
# Configuration items for graphics
# Position of text relative to graph
graphic_item=opts.GraphicItem(
# Control the overall position
left="85%",
top="45%",
),
children=[
# # opts.GraphicRect controls the display of the box
# # If you don't need the box, remove the paragraph
# opts.GraphicRect(
# # Text box position
# graphic_item=opts.GraphicItem(
# z=100, the display position of the # z axis
# left="center", # left
# top="middle", # bottom position
#).
# # textbox shape
# graphic_shape_opts=opts.GraphicShapeOpts(
# width=420, # width
# height=180, # height
#).
# # text box style
# graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
# fill="# FFF ", # text box fill color
# stroke="#00008B", # border color
# line_width=10, # border width
# shadow_blur=8, # shadow correlation
# shadow_offset_x=3
# shadow_offset_y=3
# shadow_color="rgba(0,0,0,0.3)", # shadow color
#).
#).
# config text
opts.GraphicText(
Position of text --> Position of text relative to text box
graphic_item=opts.GraphicItem(
left="center",
top='middle',
z=100.# display position
scale=[1.1].# scaling
),
graphic_textstyle_opts=opts.GraphicTextStyleOpts(
# Text message
text='I love Tiananmen In Beijing',
font="13px Microsoft YaHei".# font and font size
text_align='left'.Align horizontally to the left
text_vertical_align='middle'.# Vertical alignment: Default None,
Color and width of the # font
graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
fill='#ffdf22'.# color
line_width=1.2.# width)))]))# 5 series configuration items
geo.set_series_opts(
# tag configuration
label_opts=opts.LabelOpts(
is_show=False))# 6. Generate files
geo.render('./ Flow map.html ')
Copy the code
(2) Map the whole country using the national epidemic data as of 22:37 on 17 February 2020 as an example
National epidemic data table as of 22:37, 17 February 2020 (part)
city | time | deaths | Number of cure | Number of suspected | provinces | Confirmed the number |
---|---|---|---|---|---|---|
China | As at 22.37 hours, 17 February | 1772 | 1127 | 9 7264 | Asia | 70642 |
China | As at 22.37 hours, 17 February | 105 | 1425 | 1563 | The added value of, | 2048 |
hubei | As at 22.37 hours, 17 February | 1696 | 6693 | 0 | hubei | 58182 |
wuhan | As at 22.37 hours, 17 February | 1309 | 3507 | 0 | hubei | 41152 |
xiaogan | As at 22.37 hours, 17 February | 70 | 449 | 0 | hubei | 3279 |
huanggang | As at 22.37 hours, 17 February | 78 | 839 | 0 | hubei | 2831 |
jingzhou | As at 22.37 hours, 17 February | 37 | 305 | 0 | hubei | 1501 |
ezhou | As at 22.37 hours, 17 February | 35 | 244 | 0 | hubei | 1274 |
suizhou | As at 22.37 hours, 17 February | 24 | 140 | 0 | hubei | 1267 |
xiangyang | As at 22.37 hours, 17 February | 20 | 151 | 0 | hubei | 1155 |
Yellowstone | As at 22.37 hours, 17 February | 15 | 207 | 0 | hubei | 983 |
jingmen | As at 22.37 hours, 17 February | 33 | 132 | 0 | hubei | 915 |
yichang | As at 22.37 hours, 17 February | 24 | 156 | 0 | hubei | 895 |
xianning | As at 22.37 hours, 17 February | 10 | 181 | 0 | hubei | 861 |
shiyan | As at 22.37 hours, 17 February | 2 | 126 | 0 | hubei | 612 |
xiantao | As at 22.37 hours, 17 February | 19 | 107 | 0 | hubei | 531 |
tianmen | As at 22.37 hours, 17 February | 10 | 39 | 0 | hubei | 485 |
enshi | As at 22.37 hours, 17 February | 4 | 82 | 0 | hubei | 249 |
qianjiang | As at 22.37 hours, 17 February | 6 | 18 | 0 | hubei | 182 |
Shennongjia Forest District | As at 22.37 hours, 17 February | 0 | 10 | 0 | hubei | 10 |
guangdong | As at 22.37 hours, 17 February | 4 | 524 | 1 | guangdong | 1322 |
shenzhen | As at 22.37 hours, 17 February | 2 | 152 | 0 | guangdong | 415 |
Guangzhou | As at 22.37 hours, 17 February | 0 | 131 | 0 | guangdong | 339 |
Code implementation:
# Import draw module
from pyecharts.charts import Map
# Import configuration module
from pyecharts import options as opts
Import the theme module
from pyecharts.globals import ThemeType
import pandas as pd
Instantiate the object
map = Map(
Initial configuration
init_opts=opts.InitOpts(
width='900px',
height='500px',
theme=ThemeType.CHALK, Topic #
page_title='Map of China'.# page name))# Prepare data -- number of confirmed cases by province
data = pd.read_excel('./ Epidemic data as of 22:37, 17 February.)
print('data:\n', data)
# Get the data for each province in China first
Determine the bool array -- province data in the province = city line
mask = data.loc[:, 'province'] == data.loc[:, 'city']
# filter data
data = data.loc[mask, ['province'.'Confirmed number']]
print('data:\n', data)
# prepared data_pair
data_pair = [(k, v) for k, v in zip(data.loc[:, 'province'].tolist(), data.loc[:, 'Confirmed number'].tolist())]
print('data_pair:\n', data_pair)
# 2. Add data
map.add(
series_name='Epidemic data as of 22:37, 17 February'.# legend name
data_pair=data_pair, # data format: [(k1,v1),(k2,v2)...
maptype='china'.# Map type
is_map_symbol_show=False.# Cancel the checkmark
)
# 3 Global configuration
map.set_global_opts(
# title Settings
title_opts=opts.TitleOpts(
title='Epidemic Data in China',
subtitle='Python0421 class of Guangzhou Branch',
pos_top='3%'
),
# legend
legend_opts=opts.LegendOpts(
is_show=True,
pos_top='3%'
),
# set VisualMap
visualmap_opts=opts.VisualMapOpts(
is_show=True.# show
type_='color'.# use color to distinguish different values,
min_=0.# the minimum
max_=60000.# maximum value,
is_piecewise=True.# Enable segmented display
pieces=[
{"min": 10001."label": "10000" >."color": "#4b0101"},
{"max": 10000."min": 5001."label": "5000" >."color": "#4a0100"},
{"max": 5000."min": 1001."label": "1000" >."color": "#8A0808"},
{"max": 1000."min": 500."label": "500-1000"."color": "#B40404"},
{"max": 499."min": 108."label": "100-499"."color": "#DF0101"},
{"max": 99."min": 10."label": '10-99'."color": "#F78181"},
{"max": 9."min": 1."label": "1-9"."color": "#F5A9A9"},
{"max": 0."min": 0."label": "0"."color": "#FFFFFF"},
],
textstyle_opts=opts.TextStyleOpts(
color='white')))# 4 series configuration
map.set_series_opts(
label_opts=opts.LabelOpts(
is_show=True)),# 5. Generate files
map.render('./ Epidemic data as of 2237 hours, 17 February HTML ')
Copy the code
(3) Map the world using global epidemic data as of 22:37, 17 February 2020 as an example
Table 11-15 Global epidemic data as of 22:37 utc, 17 February 2020 (partial)
city | time | deaths | Number of cure | Number of suspected | provinces | Confirmed the number |
---|---|---|---|---|---|---|
Singapore | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 77 |
Japan | As at 22.37 hours, 17 February | 1 | 1 | 0 | Asia | 519 |
South Korea | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 30 |
Thailand | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 35 |
Malaysia | As at 22.37 hours, 17 February | 0 | 1 | 4 | Asia | 22 |
Germany | As at 22.37 hours, 17 February | 0 | 1 | 3 | The European | 16 |
The United States | As at 22.37 hours, 17 February | 0 | 1 | 0 | In North America | 15 |
Vietnam | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 16 |
The French | As at 22.37 hours, 17 February | 1 | 1 | 0 | The European | 12 |
Canada | As at 22.37 hours, 17 February | 0 | 1 | 9 | In North America | 8 |
Australia | As at 22.37 hours, 17 February | 0 | 1 | 0 | Oceania | 15 |
The united Arab emirates | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 9 |
Italy | As at 22.37 hours, 17 February | 0 | 1 | 2 | The European | 3 |
Spain | As at 22.37 hours, 17 February | 0 | 1 | 0 | The European | 2 |
Nepal | As at 22.37 hours, 17 February | 0 | 1 | 2 | Asia | 1 |
Sri Lanka | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 1 |
Britain | As at 22.37 hours, 17 February | 0 | 1 | 5 | The European | 9 |
The Swedish | As at 22.37 hours, 17 February | 0 | 1 | 0 | The European | 1 |
The Philippines | As at 22.37 hours, 17 February | 1 | 1 | 3 | 1 the Asian | 3 |
Egypt | As at 22.37 hours, 17 February | 0 | 1 | 0 | Africa | 1 |
In Cambodia, | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 1 |
Finland | As at 22.37 hours, 17 February | 0 | 1 | 0 | The European | 1 |
India | As at 22.37 hours, 17 February | 0 | 1 | 0 | Asia | 3 |
Russia | As at 22.37 hours, 17 February | 0 | 1 | 0 | The European | 2 |
Belgium | As at 22.37 hours, 17 February | 0 | 1 | 0 | The European | 1 |
Code implementation:
# guide package
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Map
import pandas as pd
from translate import Translator
Instantiate the object
map = Map(
Initial configuration
init_opts=opts.InitOpts(
width='900px',
height='500px',
theme=ThemeType.CHALK, Topic #
page_title='World Map'.# page name))# # Prepare data
data = pd.read_excel('./ Epidemic data as of 22:37, 17 February.)
# print('data:\n', data)
# Get data from countries around the world
Determine the bool array
mask = data.loc[:, 'province'].str.contains('states')
# filter data
data = data.loc[mask, ['city'.'Confirmed number']]
print('data:\n', data)
# If you draw a world map, it will not support Chinese by default
# Translate Chinese into English -->translate
PIP install translate
def translate_country_name(country_name) :
Param country_name: Chinese country name: return: English country name """
Instantiate the object
translator = Translator(from_lang='chinese', to_lang='english')
# 2. Translate
english_country_nam = translator.translate(country_name)
# 3. Return
return english_country_nam
# transform calls custom functions
data.loc[:, 'Country name _English'] = data.loc[:, 'city'].transform(translate_country_name)
print('data:\n',data)
Build data_pair data
data_pair = [(k, v) for k, v in zip(data.loc[:, 'Country name _English'].tolist(), data.loc[:, 'Confirmed number'].tolist())]
#
print('data_pair:\n', data_pair)
data_pair = [('China'.70642), ('Singapore'.77), ('Japan'.519), ('South Korea'.30), ('Thailand'.35),
('Malaysia'.22), ('Germany'.16), ('US'.15), ('Vietnam'.16), ('France'.12), ('Canada'.8),
('Australia'.15), ('United Arab Emirates'.9), ('Italy'.3), ('Spain'.2), ('Nepal'.1), ('Sri Lanka'.1),
('UK'.9), ('Swedish'.1), ('Philippines'.3), ('Egypt'.1), ('Cambodia'.1), ('Finland'.1), ('India'.3),
('Russia'.2), ('Belgium'.1)]
#
# 2. Add data
map.add(
series_name='World epidemic data as of 2237 hours, 17 February',
data_pair=data_pair,
maptype='world',
is_map_symbol_show=False
)
# 3. Set the global configuration
map.set_global_opts(
# title Settings
title_opts=opts.TitleOpts(
title='World Epidemic Data',
subtitle='Python0421 class of Guangzhou Branch',
pos_top='3%'
),
# legend
legend_opts=opts.LegendOpts(
is_show=True,
pos_top='3%'
),
# set VisualMap
visualmap_opts=opts.VisualMapOpts(
is_show=True.# show
type_='color'.# use color to distinguish different values,
min_=0.# the minimum
max_=80000.# maximum value,
is_piecewise=True.# Enable segmented display
pieces=[
{"min": 10001."label": "10000" >."color": "#4b0101"},
{"max": 10000."min": 5001."label": "5000" >."color": "#4a0100"},
{"max": 5000."min": 1001."label": "1000" >."color": "#8A0808"},
{"max": 1000."min": 500."label": "500-1000"."color": "#B40404"},
{"max": 499."min": 108."label": "100-499"."color": "#DF0101"},
{"max": 99."min": 10."label": '10-99'."color": "#F78181"},
{"max": 9."min": 1."label": "1-9"."color": "#F5A9A9"},
{"max": 0."min": 0."label": "0"."color": "#FFFFFF"},
],
textstyle_opts=opts.TextStyleOpts(
color='white')))# 4. Set the series configuration
map.set_series_opts(
label_opts=opts.LabelOpts(
is_show=False)),# 5. Generate files
map.render('./ World map of epidemic data. HTML ')
Copy the code
7. Combine China map and world map
Code implementation:
# Import draw module
from pyecharts.charts import Map
# Import configuration module
from pyecharts import options as opts
Import the theme module
from pyecharts.globals import ThemeType
import pandas as pd
from pyecharts.charts import Grid, Page
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Chinese map = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Instantiate the object
map_china = Map(
Initial configuration
init_opts=opts.InitOpts(
width='900px',
height='500px',
theme=ThemeType.CHALK, Topic #
page_title='Map of China'.# page name))# Prepare data -- number of confirmed cases by province
data = pd.read_excel('./ Epidemic data as of 22:37, 17 February.)
print('data:\n', data)
# Get the data for each province in China first
Determine the bool array -- province data in the province = city line
mask = data.loc[:, 'province'] == data.loc[:, 'city']
# filter data
data_china = data.loc[mask, ['province'.'Confirmed number']]
print('data_china:\n', data_china)
# prepared data_pair
data_pair_china = [(k, v) for k, v in zip(data_china.loc[:, 'province'].tolist(), data_china.loc[:, 'Confirmed number'].tolist())]
print('data_pair_china:\n', data_pair_china)
# 2. Add data
map_china.add(
series_name='Epidemic data as of 22:37, 17 February'.# legend name
data_pair=data_pair_china, # data format: [(k1,v1),(k2,v2)...
maptype='china'.# Map type
is_map_symbol_show=False.# Cancel the checkmark
)
# 3 Global configuration
map_china.set_global_opts(
# title Settings
title_opts=opts.TitleOpts(
title='Epidemic Data in China',
subtitle='Python0421 class of Guangzhou Branch',
pos_top='3%'
),
# legend
legend_opts=opts.LegendOpts(
is_show=True,
pos_top='3%'
),
# set VisualMap
visualmap_opts=opts.VisualMapOpts(
is_show=True.# show
type_='color'.# use color to distinguish different values,
min_=0.# the minimum
max_=60000.# maximum value,
is_piecewise=True.# Enable segmented display
pieces=[
{"min": 10001."label": "10000" >."color": "#4b0101"},
{"max": 10000."min": 5001."label": "5000" >."color": "#4a0100"},
{"max": 5000."min": 1001."label": "1000" >."color": "#8A0808"},
{"max": 1000."min": 500."label": "500-1000"."color": "#B40404"},
{"max": 499."min": 108."label": "100-499"."color": "#DF0101"},
{"max": 99."min": 10."label": '10-99'."color": "#F78181"},
{"max": 9."min": 1."label": "1-9"."color": "#F5A9A9"},
{"max": 0."min": 0."label": "0"."color": "#FFFFFF"},
],
textstyle_opts=opts.TextStyleOpts(
color='white')))# 4 series configuration
map_china.set_series_opts(
label_opts=opts.LabelOpts(
is_show=True)),# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = world map = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
from translate import Translator
Instantiate the object
map_world = Map(
Initial configuration
init_opts=opts.InitOpts(
width='900px',
height='500px',
theme=ThemeType.CHALK, Topic #
page_title='World Map'.# page name))# Get data from countries around the world
Determine the bool array
mask = data.loc[:, 'province'].str.contains('states')
# filter data
data_world = data.loc[mask, ['city'.'Confirmed number']]
print('data_world:\n', data_world)
# If you draw a world map, it will not support Chinese by default
# Translate Chinese into English -->translate
PIP install translate
def translate_country_name(country_name) :
Param country_name: Chinese country name: return: English country name """
Instantiate the object
translator = Translator(from_lang='chinese', to_lang='english')
# 2. Translate
english_country_nam = translator.translate(country_name)
# 3. Return
return english_country_nam
# transform calls custom functions
data_world.loc[:, 'Country name _English'] = data_world.loc[:, 'city'].transform(translate_country_name)
print('data_world:\n', data_world)
Build data_pair data
data_pair_world = [(k, v) for k, v in
zip(data_world.loc[:, 'Country name _English'].tolist(), data_world.loc[:, 'Confirmed number'].tolist())]
#
print('data_pair_world:\n', data_pair_world)
data_pair_world = [('China'.70642), ('Singapore'.77), ('Japan'.519), ('South Korea'.30), ('Thailand'.35),
('Malaysia'.22), ('Germany'.16), ('US'.15), ('Vietnam'.16), ('France'.12), ('Canada'.8),
('Australia'.15), ('United Arab Emirates'.9), ('Italy'.3), ('Spain'.2), ('Nepal'.1),
('Sri Lanka'.1),
('UK'.9), ('Swedish'.1), ('Philippines'.3), ('Egypt'.1), ('Cambodia'.1), ('Finland'.1),
('India'.3),
('Russia'.2), ('Belgium'.1)]
#
# 2. Add data
map_world.add(
series_name='World epidemic data as of 2237 hours, 17 February',
data_pair=data_pair_world,
maptype='world',
is_map_symbol_show=False
)
# 3. Set the global configuration
map_world.set_global_opts(
# title Settings
title_opts=opts.TitleOpts(
title='World Epidemic Data',
subtitle='Python0421 class of Guangzhou Branch',
pos_top='3%'
),
# legend
legend_opts=opts.LegendOpts(
is_show=True,
pos_top='3%'
),
# set VisualMap
visualmap_opts=opts.VisualMapOpts(
is_show=True.# show
type_='color'.# use color to distinguish different values,
min_=0.# the minimum
max_=80000.# maximum value,
is_piecewise=True.# Enable segmented display
pieces=[
{"min": 10001."label": "10000" >."color": "#4b0101"},
{"max": 10000."min": 5001."label": "5000" >."color": "#4a0100"},
{"max": 5000."min": 1001."label": "1000" >."color": "#8A0808"},
{"max": 1000."min": 500."label": "500-1000"."color": "#B40404"},
{"max": 499."min": 108."label": "100-499"."color": "#DF0101"},
{"max": 99."min": 10."label": '10-99'."color": "#F78181"},
{"max": 9."min": 1."label": "1-9"."color": "#F5A9A9"},
{"max": 0."min": 0."label": "0"."color": "#FFFFFF"},
],
textstyle_opts=opts.TextStyleOpts(
color='white')))# 4. Set the series configuration
map_world.set_series_opts(
label_opts=opts.LabelOpts(
is_show=False)),# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = map of China, the world map = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Instantiate the object
grid = Grid(
init_opts=opts.InitOpts(
width='1200px',
height='1600px',
theme=ThemeType.PURPLE_PASSION
)
)
# 2. Add data
grid.add(
chart=map_china, # chart
grid_opts=opts.GridOpts(
pos_top='3%',
height='30%',
),
grid_index=0,
is_control_axis_index=True
)
grid.add(
chart=map_world,
grid_opts=opts.GridOpts(
pos_top='40%',
height='50%',
),
grid_index=1,
is_control_axis_index=True
)
# 3. Generate files
grid.render('./ Combine China map and world map.html ')
# Sequence multigraph
Instantiate the object
page = Page(
page_title='Combine China map and World Map'.# page name
interval=0.# legend interval
layout=Page.DraggablePageLayout
)
# 2, t add data
page.add(map_china)
page.add(map_world)
#
# # 3. Generate files
page.render("./ Combine China map and world map.html")
Copy the code