700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python爬虫实战 pyecharts模块 Python实现中国地铁数据可视化

Python爬虫实战 pyecharts模块 Python实现中国地铁数据可视化

时间:2019-05-23 20:51:59

相关推荐

Python爬虫实战 pyecharts模块 Python实现中国地铁数据可视化

前言

利用Python实现中国地铁数据可视化。废话不多说。

让我们愉快地开始吧~

开发工具

Python 版本:3.6.4

相关模块:

requests模块;

wordcloud模块;

熊猫模块;

numpy模块;

杰巴模块;

pyecharts模块;

matplotlib模块;

以及一些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 = '/service/subway?_1555502190153&srhdata=' + 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 = '/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 = [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)

已经开通地铁的城市数据,还有各个城市的地铁线路数。

32个城市开通地铁

城市分布情况

大部分都是省会城市,还有个别经济实力强的城市。

线路数量分布情况

可以看到大部分还是在「0-5」这个阶段的,当然最少为1条线。

# 哪个城市哪条线路地铁站最多print(df_line.sort_values(by='station', ascending=False))

哪个城市哪条线路地铁站最多

北京10号线第一,重庆3号线第二

去除重复换乘站数据

# 去除重复换乘站的地铁数据df_station = df.groupby(['city', 'station']).count().reset_index()print(df_station)

包含3034个地铁站

减少了近400个地铁站

接下来看一下哪个城市地铁站最多

# 统计每个城市包含地铁站数(已去除重复换乘站)print(df_station.groupby(['city']).count().reset_index().sort_values(by='station', ascending=False))

武汉居然有那么多地铁站

实现一下新周刊中的操作,生成地铁名词云

def create_wordcloud(df):"""生成地铁名词云"""# 分词text = ''for line in df['station']:text += ' '.join(jieba.cut(line, cut_all=False))text += ' 'backgroud_Image = plt.imread('rocket.jpg')wc = WordCloud(background_color='white',mask=backgroud_Image,font_path='C:\Windows\Fonts\华康俪金黑W8.TTF',max_words=1000,max_font_size=150,min_font_size=15,prefer_horizontal=1,random_state=50,)wc.generate_from_text(text)img_colors = ImageColorGenerator(backgroud_Image)wc.recolor(color_func=img_colors)# 看看词频高的有哪些process_word = WordCloud.process_text(wc, text)sort = sorted(process_word.items(), key=lambda e: e[1], reverse=True)print(sort[:50])plt.imshow(wc)plt.axis('off')wc.to_file("地铁名词云.jpg")print('生成词云成功!')create_wordcloud(df_station)

展示词云图

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。