利用Python实现中国地铁数据可视化 。废话不多说 。
让我们愉快地开始吧~
开发工具Python版本:3.6.4
相关模块:requests模块;
wordcloud模块;
pandas模块;
numpy模块;
jieba模块;
pyecharts模块;
matplotlib模块;
【Python爬虫实战,pyecharts模块,Python实现中国地铁数据可视化】以及一些Python自带的模块 。
环境搭建安装Python并添加到环境变量,pip安装需要的相关模块即可 。
本次通过对地铁线路数据的获取,对城市分布情况数据进行可视化分析 。
分析获取地铁信息获取从高德地图上获取 。

文章插图
上面主要获取城市的「id」,「cityname」及「名称」 。
用于拼接请求网址,进而获取地铁线路的具体信息 。

文章插图
找到请求信息,获取各个城市的地铁线路以及线路中站点详情 。
获取数据具体代码
import jsonimport requestsfrom bs4 import BeautifulSoupheaders = { 'user-agent': 'Mozilla/5.0 (windows NT 6.1; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}def get_message(ID, cityname, name):"""地铁线路信息获取"""url = 'http://map.amap.com/service/subway?_1555502190153&srhdata=https://www.isolves.com/it/cxkf/yy/Python/2021-12-08/' + ID + '_drw_' + cityname + '.json'response = requests.get(url=url, headers=headers)html = response.textresult = json.loads(html)for i in result['l']:for j in i['st']:# 判断是否含有地铁分线if len(i['la']) > 0:print(name, i['ln'] + '(' + i['la'] + ')', j['n'])with open('subway.csv', 'a+', encoding='gbk') as f:f.write(name + ',' + i['ln'] + '(' + i['la'] + ')' + ',' + j['n'] + 'n')else:print(name, i['ln'], j['n'])with open('subway.csv', 'a+', encoding='gbk') as f:f.write(name + ',' + i['ln'] + ',' + j['n'] + 'n')def get_city():"""城市信息获取"""url = 'http://map.amap.com/subway/index.html?&1100'response = requests.get(url=url, headers=headers)html = response.text# 编码html = html.encode('ISO-8859-1')html = html.decode('utf-8')soup = BeautifulSoup(html, 'lxml')# 城市列表res1 = soup.find_all(class_="city-list fl")[0]res2 = soup.find_all(class_="more-city-list")[0]for i in res1.find_all('a'):# 城市ID值ID = i['id']# 城市拼音名cityname = i['cityname']# 城市名name = i.get_text()get_message(ID, cityname, name)for i in res2.find_all('a'):# 城市ID值ID = i['id']# 城市拼音名cityname = i['cityname']# 城市名name = i.get_text()get_message(ID, cityname, name)if __name__ == '__main__':get_city()获取数据结果展示
文章插图
3541个地铁站点
数据可视化先对数据进行清洗,去除重复的换乘站信息 。
from wordcloud import WordCloud, ImageColorGeneratorfrom pyecharts import Line, Barimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport jieba# 设置列名与数据对齐pd.set_option('display.unicode.ambiguous_as_wide', True)pd.set_option('display.unicode.east_asian_width', True)# 显示10行pd.set_option('display.max_rows', 10)# 读取数据df = pd.read_csv('subway.csv', header=None, names=['city', 'line', 'station'], encoding='gbk')# 各个城市地铁线路情况df_line = df.groupby(['city', 'line']).count().reset_index()print(df_line)通过城市及地铁线路进行分组,得到全国地铁线路总数 。
文章插图
183条地铁线路
def create_map(df):# 绘制地图value = https://www.isolves.com/it/cxkf/yy/Python/2021-12-08/[i for i in df['line']]attr = [i for i in df['city']]geo = Geo("已开通地铁城市分布情况", title_pos='center', title_top='0', width=800, height=400, title_color="#fff", background_color="#404a59", )geo.add("", attr, value, is_visualmap=True, visual_range=[0, 25], visual_text_color="#fff", symbol_size=15)geo.render("已开通地铁城市分布情况.html")def create_line(df):"""生成城市地铁线路数量分布情况"""title_len = df['line']bins = [0, 5, 10, 15, 20, 25]level = ['0-5', '5-10', '10-15', '15-20', '20以上']len_stage = pd.cut(title_len, bins=bins, labels=level).value_counts().sort_index()# 生成柱状图attr = len_stage.indexv1 = len_stage.valuesbar = Bar("各城市地铁线路数量分布", title_pos='center', title_top='18', width=800, height=400)bar.add("", attr, v1, is_stack=True, is_label_show=True)bar.render("各城市地铁线路数量分布.html")# 各个城市地铁线路数df_city = df_line.groupby(['city']).count().reset_index().sort_values(by='line', ascending=False)print(df_city)create_map(df_city)create_line(df_city)
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 68 个 Python 内置函数详解
- Python编码封装
- 盘点Python中4种读取json文件和提取json文件内容的方法
- 10分钟学会用Python轻松玩转Excel
- Python中级精华-临界区加锁
- 用Python直观查看贵州茅台股票交易数据
- 6个实用的 Python 自动化脚本,你学会了吗?
- 异步IO Python语法-多进程、多线程、协程
- 2022 python图形界面框架推荐
- 初识python正则表达式
