前言
利用Python实作中国地铁资料可视化,废话不多说,
让我们愉快地开始吧~
开发工具
Python版本:3.6.4
相关模块:
requests模块;
wordcloud模块;
pandas模块;
numpy模块;
jieba模块;
pyecharts模块;
matplotlib模块;
以及一些Python自带的模块,
环境搭建
很多人学习蟒蛇,不知道从何学起, 很多人学习寻找python,掌握了基本语法之后,不知道在哪里案例上手, 很多已经可能知道案例的人,却不怎么去学习更多高深的知识, 这三类人,我给大家提供一个好的学习平台,免费获取视频教程,电子书,以及课程的源代码! QQ群:101677771 欢迎加入,一起讨论学习
安装Python并添加到环境变量,pip安装需要的相关模块即可,
本次通过对地铁线路资料的获取,对城市分布情况资料进行可视化分析,
分析获取
地铁信息获取从高德地图上获取,
上面主要获取城市的「id」,「cityname」及「名称」,
用于拼接请求网址,进而获取地铁线路的具体信息,
找到请求信息,获取各个城市的地铁线路以及线路中站点详情,
获取资料
具体代码
import json
import requests
from bs4 import BeautifulSoup
headers = {'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.cnblogs.com/sn5200/p/+ ID +'_drw_' + cityname + '.json'
    response = requests.get(url=url, headers=headers)
    html = response.text
    result = 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, ImageColorGenerator
from pyecharts import Line, Bar
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import 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.cnblogs.com/sn5200/p/[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.index
    v1 = len_stage.values
    bar = 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)展示词云图

 
							 
										
										 
										
										 
										
										
										 
										
										 
										
										 
										
										
0 评论