Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to realize the Visualization of epidemic Map on Mac

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use Python to visualize the epidemic map on Mac". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Core ideas

The core of the epidemic map lies in the collation and visualization of epidemic data.

Epidemic data collation

The epidemic data in this paper are compiled from the public data of NetEase News and are only used for demo display. The specific address of the data has been stated in the code: this address is a Get request, you can first copy the address to the browser to view the data format. The data format of the server response after a successful request is as follows (only the data we need is listed in this article.

Parameter type remarks codeint

MsgString

DataObject

Parameters in data

Parameter type remarks the number of confirmed cases in each prefecture-level city of listList

Parameters in Object

Parameter type remarks nameString prefecture-level city name (abbreviation) visualization of epidemic situation data of confirmed number of confirmint in provinceString province

Map is a common tool for data visualization, we use map to show the specific distribution of the epidemic. This paper uses the open source pyecharts project, which is convenient for developers to use for map display. Among them, pyecharts is a class library to help generate Echarts charts; and Echarts is Baidu's open source data visualization JS library that supports 12 types of charts, such as line chart, bar chart, scatter chart, K chart, pie chart, radar chart, chord chart, force-oriented layout chart, map, dashboard, funnel chart, event river chart, etc., and can run smoothly on PC and mobile devices, compatible with the vast majority of current browsers. Pyecharts is an extension of Echarts based on Python.

Detailed explanation of the principle

Next, this article will explain in detail how to build the environment, integrate data, use pyecharts for data visualization, and how to debug the project.

Environment building

In order to develop this feature quickly and reduce the amount of code as much as possible, this demo chose to use Python for development. To do this, we should prepare the development environment for Python and import the python base library.

Install the Python environment

Mac has its own Python2.7.

Install pip

Pip is a Python package management tool, which can be used to quickly find, download, install, uninstall Python packages, etc. If you downloaded the latest version of the installation package on python.org, the system already comes with this tool. In addition, Python 2.7.9 + and Python 3.4 + and above come with pip tools. You can use the "pip-version" command line to view the current version of pip.

If the Python environment is not configured on this machine, we can install it online by typing the following two lines of command on the terminal

$curl https://bootstrap.pypa.io/get-pip.py-o get-pip.py $sudo python get-pip.py plugins required for the installation project

In the code, it is not difficult to find that we have imported some open source libraries:

Import mathimport timefrom fake_useragent import UserAgent from pyecharts.charts import Mapfrom pyecharts import options as optsimport requestsimport jsonimport sys

Plug-ins needed to request network data:

Pip install fake_useragent # disguises the request and randomly generates the UserAgentpip install requests # HTTP request library.

Plugins to be used for map display:

Pip install echarts-countries-pypkg # World Map pip install echarts-china-provinces-pypkg # Provincial Map of China pip install echarts-china-cities-pypkg # City Map of China

We copy the above command line to the terminal and execute it line by line.

Data integration & filtering

The code is still simple and clear, we can directly use the requests library to build a GET request, the server response data is "epidemic situation in all cities in the country."

Ua = UserAgent (verify_ssl=False) headers = {'User-Agent': ua.random} url = "https://c.m.163.com/ug/api/wuhan/app/index/feiyan-data-list?t=1580469818264"def getEpidemicInfo (url): try: response = requests.get (url) Headers=headers) print (response.status_code) if response.status_code = 200: content_field = json.loads (response.text) epidemicInfo = content_field ['data'] [' list'] return epidemicInfo else: print ('request error code:' + response.status_code) return None except Exception as e: print ('there is a problem with this page!' , e) return None

The t in the request address represents a timestamp. If we enter the above code, the computer will output the data in the above-mentioned format. Note: after getting the data, we need to filter. We only need to get the epidemic information of the prefecture-level cities contained in a province or autonomous prefecture or the subordinate districts and counties contained in a municipality directly under the Central Government.

We filter the relevant data through the following code:

# generate provincial epidemic situation list def makedict (list): cityList = {} for item in list: for k V in item.items (): # 1 if v = = sys.argv [1]: # 2 if str (item ["confirm"]). Isdigit (): # 3 if v = = "Beijing" or v = "Shanghai" or v = "Tianjin": cityList ['name'] + 'District'] = int (item ["confirm"]) elif "Autonomous Prefecture" in v: continue else: cityList [item ['name'] +' City'] = int (item ["confirm"]) return cityList

Sys.argv [1] is a parameter pass, representing the provinces, autonomous regions, municipalities directly under the Central Government or special administrative regions that we enter manually, such as Zhejiang, Xinjiang, Beijing, Hong Kong, etc.

The keyword "confirm" is used to match the value value of the response result, which is mentioned in the epidemic data integration above and represents the number of outbreaks in the current city.

Pyecharts is adapted according to the full name of the city. Here, you need to check the prefecture-level cities or subordinate districts and counties in the data format. If a city uses an abbreviation, it needs to be debugged (for example, the name returned by the API is Enshi, then we need to adapt to Enshi Tujia and Miao Autonomous Prefecture) to prevent abnormal map display.

For example, when we import Zhejiang, the final data format of the computer output is:

{Huzhou: 9, Lishui: 16, Zhoushan: 7, Quzhou: 15, Jinhua: 47, Jiaxing: 30, Shaoxing: 33, Ningbo: 126, Taizhou: 124, Hangzhou: 151, Wenzhou: 396} data visualization

This is the core step. The dict in the makeEpidemicInfoMap method corresponds to the data we have filtered:

Def makeEpidemicInfoMap (dict): # provinces and municipalities province_distribution = dict value = province_distribution.values () print (province_distribution) title = str (int (time.strftime ("% Y%m%d")-1) + sys.argv [1] + epidemic Map epidemicCount = [] for k V in dict.items (): epidemicCount.append (v) # 1 epidemicCount.sort (reverse=True) maxEpidemic = handle (epidemicCount.pop (0)) maxEpidemic = int (maxEpidemic) # 2 map = Map () # 3 map.set_global_opts (title_opts=opts.TitleOpts (title=title), visualmap_opts=opts.VisualMapOpts (max_=200, is_piecewise=True) Pieces= [{"max": 9999999, "min": maxEpidemic, "label": ">" + str (maxEpidemic), "color": "# 780707"}, # data range segmentation Color separation You can assign the size {"max": int (maxEpidemic), "min": int (maxEpidemic / 8) * 7, "label": str (int (maxEpidemic / 8) * 7) + "-" + str (int (maxEpidemic)) according to the data size. "color": "# B40404"}, {"max": int (maxEpidemic / 8) * 7, "min": int (maxEpidemic / 8) * 4 "label": str (int (maxEpidemic / 8) * 4) + "-" + str (int (maxEpidemic / 8) * 7-1), "color": "# CD1111"} {"max": int (maxEpidemic / 8) * 4, "min": int (maxEpidemic / 8), "label": str (int (maxEpidemic / 8)) + "-" + str (maxEpidemic / 8) * 4-1) "color": "# F68181"}, {"max": int (maxEpidemic / 8), "min": 1, "label": "1 -" + str (int (maxEpidemic / 8)), "color": "# F5A9A9"} {"max": 0, "min": 0, "label": "0", "color": "# FFFFFF"},],) # most big data range Segment) # 4 map.add (title, data_pair=province_distribution.items (), maptype=sys.argv [1], is_roam=True) map.render (sys.argv [1] + 'epidemic map .html')

Descend all cities according to the number of diagnosed cities in the selected province and get the name of the city with the largest number of confirmed cases in the current province. MaxEpidemic is closest to the high number of confirmed cases in the city. For example, if the number of confirmed cases in the most seriously affected cities in the province is "357", then maxEpidemic=300, this parameter is introduced to make the map more clear and intuitive.

Mapping with PyEcharts requires initialization of Map objects for visualization of geographic data.

Map is set in builder mode, where VisualMapOpts is the visual mapping configuration item of PyEcharts.

# specify the maximum value of the visualMapPiecewise component. Whether max = 100 # is segmented is_piecewise: bool = False, # the scope of each paragraph customized, as well as the text of each paragraph, and the special style of each paragraph. For example: # pieces: [# {"min": 1500}, / / No max is specified, which means that the max is Infinity. # {"min": 900, "max": 1500}, # {"min": 310, "max": 1000}, # {"min": 1000, "max": 1000}, # {"min": 10, "max": 200, "label":'10 to 200 (custom label)'}, # {"value": 123, "label": '123 (custom special color)' "color": 'grey'}, / / indicates that if value equals 123, # {"max": 5} / / No min is specified Indicates that the min is infinite (- Infinity). #]

Detailed configuration can be found on the official website of PyEcharts. The scope here is divided into six sections, and the range of each section is dynamically adjusted according to the maxEpidemic calculated above, in order to ensure the visual effect of the epidemic map. I have only made a very brief range model for reference only.

4.

Debug

Execute python map.py [province], such as:

You will get a file named Zhejiang epidemic Map .html under the current directory, which can be opened directly with a browser. Is the final display effect very cool?

This is the end of the content of "how to use Python to visualize the epidemic map on Mac". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report