一、选题的背景
选择此选题是因为掌上高考是一个提供本科院校信息的网站,通过爬取该网站的数据,可以获取到各个本科院校的相关信息,如学校名称、所在地、专业设置等。通过对这些数据进行分析和可视化,可以帮助学生更好地了解各个本科院校的情况,为他们的升学选择提供参考。预期目标是通过数据分析,找出各个本科院校的特点和优势,以及不同地区、不同专业的分布情况,为学生提供更全面、准确的信息。从社会方面来看,这有助于提高学生的就业竞争力;从经济方面来看,这有助于促进教育产业的发展;从技术方面来看,这需要运用爬虫技术和数据分析技术;数据来源主要是掌上高考网站。
二、主题式网络爬虫设计方案
1. 主题式网络爬虫名称:掌上高考高校数据爬取与可视化爬虫
2. 主题式网络爬虫爬取的内容与数据特征分析:
- 爬取内容:掌上高考网站上的高校数据,包括高校名称、所在地、类型(综合类、理工类等)、排名、学科门类等信息。
- 数据特征分析:高校数据具有结构化特点,可以通过HTML标签和属性进行定位和提取。同时,由于高校数据的多样性,需要对不同类型的高校进行分类处理
3. 主题式网络爬虫设计方案概述:
- 实现思路:
(1). 确定目标网站:掌上高考网站。
(2). 分析网页结构:使用浏览器开发者工具查看网页源代码,分析大学数据的HTML标签和属性。
(3). 编写爬虫代码:根据分析结果,使用Python的第三方库编写爬虫代码,实现对高校数据的爬取。
(4). 数据清洗与存储:对爬取到的数据进行清洗和格式化处理,将数据存储到合适的数据结构中,如列表、字典等。
(5). 数据可视化:使用Python的可视化库对高校数据进行可视化展示,如绘制柱状图、折线图等。
- 技术难点:
(1). 动态加载:部分网页数据是通过JavaScript动态加载的,需要使用Selenium等工具模拟浏览器操作,获取动态加载的数据。
(2). 反爬机制:目标网站可能采用反爬机制,如设置User-Agent、限制访问频率等,需要使用代理IP、设置请求头等方式绕过反爬策略。
(3). 数据清洗:爬取到的数据可能存在缺失值、异常值等问题,需要进行数据清洗和预处理,确保数据的准确性和完整性。
三、主题页面的结构特征分析
1.主题页面的结构与特征分析:
![]()
![]()
(1).主题页面包含多个大学的信息、
(2).每个大学的信息包括学校名称、所在地、类型、排名等。
(3).页面中可能存在分页功能,需要翻页获取更多高校信息。
2. Htmls 页面解析
![]()
<div class="main-nav_mainNav__1qgwf"> 上方导航栏,其内容是学校、专业等内容分类
<div class="school-search_findBox__3C5IT">地区选择栏
<div class="school-search_listBox__at-rI">内容区
<div class="pagination_box">页面部分,用来选择页面
3.节点(标签) 查找方法与遍历方法
- 查找方法:通过调用get_size()函数获取数据总数,然后调用get_university_info()函数进行分页爬取
- 遍历方法:是在get_university_info()函数中,使用for`循环遍历每一页的数据
四、网络爬虫程序设计
Part1: 爬取查学校里面院校库的网页数据并保存为“全国大学数据.csv”文件
![]()
![]()
![]()
# 导入所需模块 import json import time from time import sleep import pandas as pd import numpy as np from bs4 import BeautifulSoup from requests_html import HTMLSession,UserAgent import random import os def get_header(): import fake_useragent location = os.getcwd() + '/fake_useragent.json' ua = fake_useragent.UserAgent(path=location) return ua.random def get_size(page=1): url = 'https://api.eol.cn/gkcx/api/?access_token=&admissions=¢ral=&department=&dual_class=&f211=&f985=&is_doublehigh=&is_dual_class=&keyword=&nature=&page={0}&province_id=&ranktype=&request_type=1&school_type=&signsafe=&size=20&sort=view_total&top_school_id=[2941]&type=&uri=apidata/api/gk/school/lists'\ .format(page) session = HTMLSession() #创建HTML会话对象 user_agent = UserAgent().random #创建随机请求头 header = {"User-Agent": user_agent} res = session.post(url, headers=header) data = json.loads(res.text) size = 0 if data["message"] == '成功---success': size = data["data"]["numFound"] return size def get_university_info(size, page_size=20): page_cnt = int(size/page_size) if size%page_size==0 else int(size/page_size)+1 print('一共{0}页数据,即将开始爬取...'.format(page_cnt)) session2 = HTMLSession() #创建HTML会话对象 df_result = pd.DataFrame() for index in range(1, page_cnt+1): print('正在爬取第 {0}/{1} 页数据'.format(index, page_cnt)) url = 'https://api.eol.cn/gkcx/api/?access_token=&admissions=¢ral=&department=&dual_class=&f211=&f985=&is_doublehigh=&is_dual_class=&keyword=&nature=&page={0}&province_id=&ranktype=&request_type=1&school_type=&signsafe=&size=20&sort=view_total&top_school_id=[2941]&type=&uri=apidata/api/gk/school/lists' \ .format(index) user_agent = UserAgent().random #创建随机请求头 header = {"User-Agent": user_agent} res = session2.post(url, headers=header) with open("res.text", "a+", encoding="utf-8") as file: file.write(res.text) data = json.loads(res.text) if data["message"] == '成功---success': df_data = pd.DataFrame(data["data"]["item"]) df_result = pd.concat([df_result, df_data], ignore_index=True) time.sleep(random.randint(5, 7)) return df_result size = get_size() df_result = get_university_info(size) df_result.to_csv('全国大学数据.csv', encoding='gbk', index=False)
![]()
![]()
Part2: 用访问量排序来查询保存下来的“全国大学数据.csv”文件
![]()
# 导入所需模块 import pandas as pd import plotly as py import numpy as np # 读取数据 university = pd.read_csv('data/全国大学数据.csv',encoding='gbk') # 对数据进行处理 university = university.loc[:,['name','nature_name','province_name','belong', 'city_name', 'dual_class_name','f211','f985','level_name' , 'type_name','view_month_number','view_total_number', 'view_week_number','rank']] c_name = ['大学名称','办学性质','省份','隶属','城市','高校层次', '211院校','985院校','级别','类型','月访问量','总访问量','周访问量','排名'] university.columns = c_name # 访问量排序 university.sort_values(by='总访问量',ascending=False).head()
![]()
Part3: 用条形图显示全国各省的 “双一流” 和 “非双一流” 高校数量
university['高校总数'] = 1 university.fillna({'高校层次': '非双一流'},inplace=True) university_by_province = university.pivot_table(index=['省份','高校层次'], values='高校总数',aggfunc='count') university_by_province.reset_index(inplace=True) university_by_province.sort_values(by=['高校总数'],ascending=False,inplace=True) #查询全国各省高校数量 import plotly.express as px fig = px.bar(university_by_province, x="省份", y="高校总数", color="高校层次") fig.update_layout( title='全国各省高校数量', xaxis_title="省份", yaxis_title="高校总数", template='ggplot2', font=dict( size=12, color="Black", ), margin=dict(l=40, r=20, t=50, b=40), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", legend=dict(yanchor="top", y=0.8, xanchor="left", x=0.78) ) fig.show()
![]()
![]()
Part4: 根据 “全国省市区行政区划.xlsx” 文件结合 “全国大学数据.csv” 中的经纬度生成全国高校地理分布图
df = pd.read_excel('./data/全国省市区行政区划.xlsx',header=1) # 筛选出层级为2的数据,并选择'全称'、'经度'和'纬度'列 df_l = df.query("层级==2").loc[:,['全称','经度','纬度']] df_l = df_l.reset_index(drop=True).rename(columns={'全称':'城市'}) df7 = university.pivot_table('大学名称','城市',aggfunc='count') df7 = df7.merge(df_l,on='城市',how='left') # 按照大学数量降序排序 df7.sort_values(by='大学名称',ascending=False) import plotly.graph_objects as go import pandas as p df7['text'] = df7['城市'] + '<br>大学总数 ' + (df7['大学名称']).astype(str)+'个' # 定义文本、颜色和范围 limits = [(0,10),(11,20),(21,50),(51,100),(101,200)] colors = ["royalblue","crimson","lightseagreen","orange","red"] cities = [] scale =.08 # 创建地理分布图对象 fig = go.Figure() # 遍历范围,筛选出对应的城市数据,并添加到地理分布图中 for i in range(len(limits)): lim = limits[i] df_sub = df7[df7.大学名称.map(lambda x: lim[0] <= x <= lim[1])] fig.add_trace(go.Scattergeo( locationmode = 'ISO-3', lon = df_sub['经度'], lat = df_sub['纬度'], text = df_sub['text'], marker = dict( size = df_sub['大学名称'], color = colors[i], line_color='rgb(40,40,40)', line_width=0.5, sizemode = 'area' ), name = '{0} - {1}'.format(lim[0],lim[1]))) # 更新地理分布图布局 fig.update_layout( title_text = '全国高校地理分布图', showlegend = True, geo = dict( scope = 'asia', landcolor = 'rgb(217, 217, 217)', ), template='ggplot2', font=dict( size=12, color="Black",), legend=dict(yanchor="top", y=1., xanchor="left", x=1) ) # 显示地理分布图 fig.show()
![]()
Part5: 针对全国高校的热度排行创建一个柱状图,并在其中创建一个散点图用来显示高校名称和周访问量。
![]()
1 import plotly.graph_objs as go
import plotly.graph_objs as go # 创建一个空的图形对象 fig=go.Figure() # 对数据按照总访问量进行降序排序 df3 = university.sort_values(by='总访问量',ascending=False) # 添加一个柱状图,表示大学名称、总访问量和颜色 fig.add_trace(go.Bar( x=df3.loc[:15,'大学名称'], y=df3.loc[:15,'总访问量'], name='总访问量', marker_color='#009473', textposition='inside', yaxis='y1' )) # 添加一个散点图,表示大学名称、周访问量和颜色 fig.add_trace(go.Scatter( x=df3.loc[:15,'大学名称'], y=df3.loc[:15,'周访问量'], name='周访问量', mode='markers+text+lines', marker_color='black', marker_size=10, textposition='top center', line=dict(color='orange',dash='dash'), yaxis='y2' )) # 更新图形布局 fig.update_layout( title='全国高校热度TOP15', xaxis_title="大学名称", yaxis_title="总访问量", template='ggplot2', font=dict( size=12, color="Black", ), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", yaxis2=dict(showgrid=True,overlaying='y',side='right',title='周访问量'), legend=dict(yanchor="top", y=1.15, xanchor="left", x=0.8) ) # 显示图形 fig.show()
![]()
![]()
Part6: 查询热度排名前十的省份内前三的学校
# 从数据集中筛选出省份、大学名称和总访问量三列 df9 = university.loc[:,['省份','大学名称','总访问量']] # 根据省份对总访问量进行降序排名,得到每个省份的前三所大学 df9['前三'] = df9.drop_duplicates()['总访问量'].groupby(by=df9['省份']).rank(method='first', ascending=False) df_10 = df9[df9['前三'].map(lambda x: True if x < 4 else False)] df_10['前三'] = df_10.前三.astype(int) # 使用pivot_table方法创建一个透视表,以省份为行索引,前三名大学为列索引,总访问量为值 df_pt = df_10.pivot_table(values='总访问量',index='省份',columns='前三') # 按照总访问量降序排列透视表,并取前10个省份 df_pt_2 = df_pt.sort_values(by=1,ascending=False)[:10] # 获取排名前三的大学名称 df_labels_1 = df9[df9.前三 == 1].set_index('省份').loc[df_pt_2.index,'大学名称'][:10] df_labels_2 = df9[df9.前三 == 2].set_index('省份').loc[df_pt_2.index,'大学名称'][:10] df_labels_3 = df9[df9.前三 == 3].set_index('省份').loc[df_pt_2.index,'大学名称'][:10] #创建x轴数据和图形对象 x = df_pt_2.index fig = go.Figure() # 添加柱状图,表示热度第一、热度第二、热度第三的大学 fig.add_trace(go.Bar( x=x, y=df_pt_2[1], name='热度第一', marker_color='indianred', textposition='inside', text=df_labels_1.values, textangle = 90 )) fig.add_trace(go.Bar( x=x, y=df_pt_2[2], name='热度第二', marker_color='lightsalmon', textposition='inside', text=df_labels_2.values, textangle = 90 )) fig.add_trace(go.Bar( x=x, y=df_pt_2[3], name='热度第三', marker_color='lightpink', textposition='inside', text=df_labels_3.values, textangle = 90 )) # 修改x轴刻度标签的角度,使标签旋转 fig.update_layout(barmode='group', xaxis_tickangle=-45) # 更新图形布局,包括标题、x轴和y轴标题、模板、字体和柱状图模式等 fig.update_layout( title='全国高校热度TOP10省份的前三名', xaxis_title="省份", yaxis_title="总访问量", template='ggplot2', font=dict( size=12, color="Black"), barmode='group', xaxis_tickangle=-45 ) fig.show()
![]()
Part7: 查询北京市热度排名前十五的学校
import plotly.graph_objs as go # 筛选出北京市的双一流高校,并取前15名 df_bj = university.query("高校层次 == '双一流' and 城市== '北京市'").iloc[:15,:] # 创建图形对象并对总访问量进行降序排序 fig=go.Figure() df3 = university.sort_values(by='总访问量',ascending=False) # 添加柱状图,展示总访问量 fig.add_trace(go.Bar( x=df_bj['大学名称'], y=df_bj['总访问量'], name='总访问量', marker_color='#009473', textposition='inside', yaxis='y1' )) # 添加散点图和折线图,展示周访问量 fig.add_trace(go.Scatter( x=df_bj['大学名称'], y=df_bj['周访问量'], name='周访问量', mode='markers+text+lines', marker_color='black', marker_size=10, textposition='top center', line=dict(color='orange',dash='dash'), yaxis='y2' )) # 更新图形布局 fig.update_layout( title='北京高校热度TOP15', xaxis_title="大学名称", yaxis_title="总访问量", template='ggplot2', font=dict( size=12, color="Black", ), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", yaxis2=dict(showgrid=True,overlaying='y',side='right',title='周访问量'), legend=dict(yanchor="top", y=1.15, xanchor="left", x=0.78) ) fig.show()
![]()
Part8: 查询全国高校按类别划分的热度图
# 从university数据框中提取'城市'、'高校层次'、'211院校'和'985院校'列,并添加一列名为'总数'的全为1的新列 df5 = university.loc[:,['城市','高校层次','211院校','985院校']] df5['总数'] = 1 # 将 '211院校' 和 '985院校' 列中的值映射为'是'或'否' df5['211院校'] = df5['211院校'].map(lambda x: '是' if x == 1 else '否') df5['985院校'] = df5['985院校'].map(lambda x: '是' if x == 1 else '否') # 将数据框重塑为以'城市'和'985院校'为索引的新数据框,并将'总数'列的值作为新数据框的值 df6 =df5.pivot_table(index=['城市','985院校'],values='总数').reset_index() df6 df6.columns # 使用plotly库绘制散点图 fig = px.scatter(university,x="省份", y="类型",size="总访问量") # 更新图表布局设置 fig.update_layout( title='全国高校按类别热度图', xaxis_title="省份", yaxis_title="院校类型", template='ggplot2', font=dict(size=12,color="Black",), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", ) fig.show()
![]()
爬虫课程设计全部代码如下:
# 导入所需模块 import os import json import time import random import numpy as np import pandas as pd import plotly as py from time import sleep import plotly.express as px from bs4 import BeautifulSoup from requests_html import HTMLSession,UserAgent def get_header(): import fake_useragent location = os.getcwd() + '/fake_useragent.json' ua = fake_useragent.UserAgent(path=location) return ua.random # 高校数据 def get_size(page=1): url = 'https://api.eol.cn/gkcx/api/?access_token=&admissions=¢ral=&department=&dual_class=&f211=&f985=&is_doublehigh=&is_dual_class=&keyword=&nature=&page={0}&province_id=&ranktype=&request_type=1&school_type=&signsafe=&size=20&sort=view_total&top_school_id=[2941]&type=&uri=apidata/api/gk/school/lists'\ .format(page) session = HTMLSession() #创建HTML会话对象 user_agent = UserAgent().random #创建随机请求头 header = {"User-Agent": user_agent} res = session.post(url, headers=header) data = json.loads(res.text) size = 0 if data["message"] == '成功---success': size = data["data"]["numFound"] return size def get_university_info(size, page_size=20): page_cnt = int(size/page_size) if size%page_size==0 else int(size/page_size)+1 print('一共{0}页数据,即将开始爬取...'.format(page_cnt)) session2 = HTMLSession() #创建HTML会话对象 df_result = pd.DataFrame() for index in range(1, page_cnt+1): print('正在爬取第 {0}/{1} 页数据'.format(index, page_cnt)) url = 'https://api.eol.cn/gkcx/api/?access_token=&admissions=¢ral=&department=&dual_class=&f211=&f985=&is_doublehigh=&is_dual_class=&keyword=&nature=&page={0}&province_id=&ranktype=&request_type=1&school_type=&signsafe=&size=20&sort=view_total&top_school_id=[2941]&type=&uri=apidata/api/gk/school/lists' \ .format(index) user_agent = UserAgent().random #创建随机请求头 header = {"User-Agent": user_agent} res = session2.post(url, headers=header) with open("res.text", "a+", encoding="utf-8") as file: file.write(res.text) data = json.loads(res.text) if data["message"] == '成功---success': df_data = pd.DataFrame(data["data"]["item"]) df_result = pd.concat([df_result, df_data], ignore_index=True) time.sleep(random.randint(5, 7)) return df_result size = get_size() df_result = get_university_info(size) df_result.to_csv('全国大学数据.csv', encoding='gbk', index=False) #查询总访问量排序下的全国大学数据文件 # 读取数据 university = pd.read_csv('data/全国大学数据.csv',encoding='gbk') # 对数据进行处理 university = university.loc[:,['name','nature_name','province_name','belong', 'city_name', 'dual_class_name','f211','f985','level_name' , 'type_name','view_month_number','view_total_number', 'view_week_number','rank']] c_name = ['大学名称','办学性质','省份','隶属','城市','高校层次', '211院校','985院校','级别','类型','月访问量','总访问量','周访问量','排名'] university.columns = c_name # 访问量排序 university.sort_values(by='总访问量',ascending=False).head() #显示全国双一流和非双一流的高校数量 university['高校总数'] = 1 university.fillna({'高校层次': '非双一流'},inplace=True) university_by_province = university.pivot_table(index=['省份','高校层次'], values='高校总数',aggfunc='count') university_by_province.reset_index(inplace=True) university_by_province.sort_values(by=['高校总数'],ascending=False,inplace=True) #查询全国各省高校数量 fig = px.bar(university_by_province, x="省份", y="高校总数", color="高校层次") fig.update_layout( title='全国各省高校数量', xaxis_title="省份", yaxis_title="高校总数", template='ggplot2', font=dict( size=12, color="Black", ), margin=dict(l=40, r=20, t=50, b=40), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", legend=dict(yanchor="top", y=0.8, xanchor="left", x=0.78) ) fig.show() #生成全国高校地理分布图 df = pd.read_excel('./data/全国省市区行政区划.xlsx',header=1) # 筛选出层级为2的数据,并选择'全称'、'经度'和'纬度'列 df_l = df.query("层级==2").loc[:,['全称','经度','纬度']] df_l = df_l.reset_index(drop=True).rename(columns={'全称':'城市'}) df7 = university.pivot_table('大学名称','城市',aggfunc='count') df7 = df7.merge(df_l,on='城市',how='left') # 按照大学数量降序排序 df7.sort_values(by='大学名称',ascending=False) import plotly.graph_objects as go import pandas as p df7['text'] = df7['城市'] + '<br>大学总数 ' + (df7['大学名称']).astype(str)+'个' # 定义文本、颜色和范围 limits = [(0,10),(11,20),(21,50),(51,100),(101,200)] colors = ["royalblue","crimson","lightseagreen","orange","red"] cities = [] scale =.08 # 创建地理分布图对象 fig = go.Figure() # 遍历范围,筛选出对应的城市数据,并添加到地理分布图中 for i in range(len(limits)): lim = limits[i] df_sub = df7[df7.大学名称.map(lambda x: lim[0] <= x <= lim[1])] fig.add_trace(go.Scattergeo( locationmode = 'ISO-3', lon = df_sub['经度'], lat = df_sub['纬度'], text = df_sub['text'], marker = dict( size = df_sub['大学名称'], color = colors[i], line_color='rgb(40,40,40)', line_width=0.5, sizemode = 'area' ), name = '{0} - {1}'.format(lim[0],lim[1]))) # 更新地理分布图布局 fig.update_layout( title_text = '全国高校地理分布图', showlegend = True, geo = dict( scope = 'asia', landcolor = 'rgb(217, 217, 217)', ), template='ggplot2', font=dict( size=12, color="Black",), legend=dict(yanchor="top", y=1., xanchor="left", x=1) ) # 显示地理分布图 fig.show() # 全国高校热度TOP15 import plotly.graph_objs as go # 创建一个空的图形对象 fig=go.Figure() # 对数据按照总访问量进行降序排序 df3 = university.sort_values(by='总访问量',ascending=False) # 添加一个柱状图,表示大学名称、总访问量和颜色 fig.add_trace(go.Bar( x=df3.loc[:15,'大学名称'], y=df3.loc[:15,'总访问量'], name='总访问量', marker_color='#009473', textposition='inside', yaxis='y1' )) # 添加一个散点图,表示大学名称、周访问量和颜色 fig.add_trace(go.Scatter( x=df3.loc[:15,'大学名称'], y=df3.loc[:15,'周访问量'], name='周访问量', mode='markers+text+lines', marker_color='black', marker_size=10, textposition='top center', line=dict(color='orange',dash='dash'), yaxis='y2' )) # 更新图形布局 fig.update_layout( title='全国高校热度TOP15', xaxis_title="大学名称", yaxis_title="总访问量", template='ggplot2', font=dict( size=12, color="Black", ), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", yaxis2=dict(showgrid=True,overlaying='y',side='right',title='周访问量'), legend=dict(yanchor="top", y=1.15, xanchor="left", x=0.8) ) # 显示图形 fig.show() #全国高校热度TOP10省份的前三名 # 从数据集中筛选出省份、大学名称和总访问量三列 df9 = university.loc[:,['省份','大学名称','总访问量']] # 根据省份对总访问量进行降序排名,得到每个省份的前三所大学 df9['前三'] = df9.drop_duplicates()['总访问量'].groupby(by=df9['省份']).rank(method='first', ascending=False) df_10 = df9[df9['前三'].map(lambda x: True if x < 4 else False)] df_10['前三'] = df_10.前三.astype(int) # 使用pivot_table方法创建一个透视表,以省份为行索引,前三名大学为列索引,总访问量为值 df_pt = df_10.pivot_table(values='总访问量',index='省份',columns='前三') # 按照总访问量降序排列透视表,取前10个省份 df_pt_2 = df_pt.sort_values(by=1,ascending=False)[:10] # 获取排名前三的大学名称 df_labels_1 = df9[df9.前三 == 1].set_index('省份').loc[df_pt_2.index,'大学名称'][:10] df_labels_2 = df9[df9.前三 == 2].set_index('省份').loc[df_pt_2.index,'大学名称'][:10] df_labels_3 = df9[df9.前三 == 3].set_index('省份').loc[df_pt_2.index,'大学名称'][:10] #创建x轴数据和图形对象 x = df_pt_2.index fig = go.Figure() # 添加柱状图,表示热度第一、热度第二、热度第三的大学 fig.add_trace(go.Bar( x=x, y=df_pt_2[1], name='热度第一', marker_color='indianred', textposition='inside', text=df_labels_1.values, textangle = 90 )) fig.add_trace(go.Bar( x=x, y=df_pt_2[2], name='热度第二', marker_color='lightsalmon', textposition='inside', text=df_labels_2.values, textangle = 90 )) fig.add_trace(go.Bar( x=x, y=df_pt_2[3], name='热度第三', marker_color='lightpink', textposition='inside', text=df_labels_3.values, textangle = 90 )) # 修改x轴刻度标签的角度,使标签旋转 fig.update_layout(barmode='group', xaxis_tickangle=-45) # 更新图形布局,包括标题、x轴和y轴标题、模板、字体和柱状图模式等 fig.update_layout( title='全国高校热度TOP10省份的前三名', xaxis_title="省份", yaxis_title="总访问量", template='ggplot2', font=dict( size=12, color="Black"), barmode='group', xaxis_tickangle=-45 ) fig.show() #查询北京市热度排名前十五的学校 import plotly.graph_objs as go # 筛选出北京市的双一流高校,并取前15名 df_bj = university.query("高校层次 == '双一流' and 城市== '北京市'").iloc[:15,:] # 创建图形对象并对总访问量进行降序排序 fig=go.Figure() df3 = university.sort_values(by='总访问量',ascending=False) # 添加柱状图,展示总访问量 fig.add_trace(go.Bar( x=df_bj['大学名称'], y=df_bj['总访问量'], name='总访问量', marker_color='#009473', textposition='inside', yaxis='y1' )) # 添加散点图和折线图,展示周访问量 fig.add_trace(go.Scatter( x=df_bj['大学名称'], y=df_bj['周访问量'], name='周访问量', mode='markers+text+lines', marker_color='black', marker_size=10, textposition='top center', line=dict(color='orange',dash='dash'), yaxis='y2' )) # 更新图形布局 fig.update_layout( title='北京高校热度TOP15', xaxis_title="大学名称", yaxis_title="总访问量", template='ggplot2', font=dict(size=12,color="Black", ), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", yaxis2=dict(showgrid=True,overlaying='y',side='right',title='周访问量'), legend=dict(yanchor="top", y=1.15, xanchor="left", x=0.78) ) fig.show() #查询全国高校按类别划分的热度图 # 从university数据框中提取'城市'、'高校层次'、'211院校'和'985院校'列,并添加一列名为'总数'的全为1的新列 df5 = university.loc[:,['城市','高校层次','211院校','985院校']] df5['总数'] = 1 # 将 '211院校' 和 '985院校' 列中的值映射为'是'或'否' df5['211院校'] = df5['211院校'].map(lambda x: '是' if x == 1 else '否') df5['985院校'] = df5['985院校'].map(lambda x: '是' if x == 1 else '否') # 将数据框重塑为以'城市'和'985院校'为索引的新数据框,并将'总数'列的值作为新数据框的值 df6 =df5.pivot_table(index=['城市','985院校'],values='总数').reset_index() df6 df6.columns # 绘制散点图 fig = px.scatter(university, x="省份", y="类型", size="总访问量" ) # 更新图表布局设置 fig.update_layout( title='全国高校按类别热度图', xaxis_title="省份", yaxis_title="院校类型", template='ggplot2', font=dict( size=12, color="Black",), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), plot_bgcolor="#fafafa", ) fig.show()
五.总结
1. 根据柱状图了解到河南的非双一流学校最多,北京的双一流学校最多。
2. 根据地图了解到国内大部分高校分在国家的东部和中部。
3. 根据柱状图了解到大家对厦门大学、四川大学比较感兴趣。
4. 根据柱状图了解到排名第一的福建省只有一所厦门大学热度超前,而四川省、湖北省、广东省、北京市的高校热度都较为平均。
5. 根据散点图了解到全国各省的综合类的热度均较为突出
综上所述,河南在高等教育方面有更多的资源和机会,而北京则拥有更多的顶尖高校。东部和中部地区的经济发展相对较好,教育资源相对集中。厦门大学和四川大学在学术研究、教学质量等方面具有较高的声誉和知名度。综合类高校在各个省份都受到较高的关注和认可。