中国88个超500万人口的大中城市都在哪里?Python动态图告诉你!

2023-10-27 15:10

本文主要是介绍中国88个超500万人口的大中城市都在哪里?Python动态图告诉你!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今日表情 ????

我国的城市层次

除港澳台外,中国一共有337个地级市(含4个直辖市)。一般综合考虑城市人口规模和城市经济发展水平等因素,可以将城市分成一线、新一线、二线、三线、四线、五线等不同层次。

下面我们来看一份第一财经新一线城市研究所发布的一份2021城市商业魅力排行榜城市层次榜单。

我国城市人口规模

如果仅仅考虑城市人口规模的话,根据最新人口普查公开数据,中国337个地级市当中,一共有88个城市超过500万个。它们是哪些城市呢?我们用Python动态图盘点一下吧!

先上图片

再上视频

最后上代码

import numpy as np 
import pandas as pd 
import geopandas as gpd 
import shapely 
from shapely import geometry as geo 
from shapely import wkt 
import geopandas as gpd 
import matplotlib.pyplot as plt 
import matplotlib.animation as  animation 
import contextily as ctximport imageio
import os 
from PIL import Imageplt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['animation.writer'] = 'html'
plt.rcParams['animation.embed_limit'] = 100def rgba_to_rgb(img_rgba):img_rgb = Image.new("RGB", img_rgba.size, (255, 255, 255))img_rgb.paste(img_rgba, mask=img_rgba.split()[3]) return img_rgb def html_to_gif(html_file, gif_file, duration=0.5):path = html_file.replace(".html","_frames")images = [os.path.join(path,x) for x in sorted(os.listdir(path))]frames = [imageio.imread(x) for x in images]if frames[0].shape[-1]==4:frames = [np.array(rgba_to_rgb(Image.fromarray(x))) for x in frames]imageio.mimsave(gif_file, frames, 'gif', duration=duration)return gif_filecmap = [
'#2E91E5',
'#1CA71C',
'#DA16FF',
'#B68100',
'#EB663B',
'#00A08B',
'#FC0080',
'#6C7C32',
'#862A16',
'#620042',
'#DA60CA',
'#0D2A63']*100def getCoords(geom):if isinstance(geom,geo.MultiPolygon):return [np.array(g.exterior) for g in geom.geoms]elif isinstance(geom,geo.Polygon):return [np.array(geom.exterior)]elif isinstance(geom,geo.LineString):return [np.array(geom)]elif isinstance(geom,geo.MultiLineString):return [np.array(x) for x in list(geom.geoms)]else:raise Exception("geom must be one of [polygon,MultiPolygon,LineString,MultiLineString]!")#底图数据
dfprovince = gpd.read_file("./data/dfprovince.geojson").set_crs("epsg:4326").to_crs("epsg:2343")
dfnanhai = gpd.read_file("./data/dfnanhai.geojson").set_crs("epsg:4326").to_crs("epsg:2343")
dfline9 =  dfnanhai[(dfnanhai["LENGTH"]>1.0)&(dfnanhai["LENGTH"]<2.0)]#散点数据
dfpoints = gpd.read_file("./data/china_big_cities.geojson").set_crs("epsg:4326").to_crs("epsg:2343")
dfpoints["point"] = dfpoints.representative_point()
dfpoints = dfpoints.query("population>=5000000") df = pd.DataFrame({"x":[pt.x for pt in dfpoints["point"]],"y": [pt.y for pt in dfpoints["point"]],"z":[x for x in dfpoints["population"]]})
df.index = [x for x in dfpoints["city"]] def bubble_map_dance(df,title = "中国超500万人口城市",filename = None,figsize = (8,6),dpi = 144,duration = 0.5,anotate_points = ["北京市","上海市","重庆市","赣州市","沈阳市"]):fig, ax_base =plt.subplots(figsize=figsize,dpi=dpi)ax_child=fig.add_axes([0.800,0.125,0.10,0.20])def plot_frame(i):ax_base.clear()ax_child.clear()#============================================================#绘制底图#============================================================#绘制省边界polygons = [getCoords(x) for x in dfprovince["geometry"]]for j,coords in enumerate(polygons):for x in coords:poly = plt.Polygon(x, fill=True, ec = "gray", fc = "white",alpha=0.5,linewidth=.8)poly_child = plt.Polygon(x, fill=True, ec = "gray", fc = "white",alpha=0.5,linewidth=.8)ax_base.add_patch(poly)ax_child.add_patch(poly_child )#绘制九段线coords = [getCoords(x) for x in dfline9["geometry"]]lines = [y for x in coords for y in x ]for ln in lines:x, y = np.transpose(ln)line = plt.Line2D(x,y,color="gray",linestyle="-.",linewidth=1.5)line_child = plt.Line2D(x,y,color="gray",linestyle="-.",linewidth=1.5)ax_base.add_artist(line)ax_child.add_artist(line_child)#设置spine格式for spine in['top','left',"bottom","right"]:ax_base.spines[spine].set_color("none")ax_child.spines[spine].set_alpha(0.5)ax_base.axis("off")#设置绘图范围bounds = dfprovince.total_boundsax_base.set_xlim(bounds[0]-(bounds[2]-bounds[0])/10, bounds[2]+(bounds[2]-bounds[0])/10)ax_base.set_ylim(bounds[1]+(bounds[3]-bounds[1])/3.5, bounds[3]+(bounds[3]-bounds[1])/100)ax_child.set_xlim(bounds[2]-(bounds[2]-bounds[0])/2.5, bounds[2]-(bounds[2]-bounds[0])/20)ax_child.set_ylim(bounds[1]-(bounds[3]-bounds[1])/20, bounds[1]+(bounds[3]-bounds[1])/2)#移除坐标轴刻度ax_child.set_xticks([]);ax_child.set_yticks([]);#============================================================#绘制散点#============================================================k = i//3+1m = i%3text = "NO."+str(len(df)+1-k) dfdata = df.iloc[:k,:].copy()dftmp = df.iloc[:k-1,:].copy()# 绘制散点图像if len(dftmp)>0:ax_base.scatter(dftmp["x"],dftmp["y"],s = 100*dftmp["z"]/df["z"].mean(),c = (cmap*100)[0:len(dftmp)],alpha = 0.3,zorder = 3)ax_child.scatter(dftmp["x"],dftmp["y"],s = 100*dftmp["z"]/df["z"].mean(),c = (cmap*100)[0:len(dftmp)],alpha = 0.3,zorder = 3)# 添加注释文字for i,p in enumerate(dftmp.index):px,py,pz = dftmp.loc[p,["x","y","z"]].tolist() if p in anotate_points:ax_base.annotate(p,xy = (px,py),  xycoords = "data",xytext = (-15,10),fontsize = 10,fontweight = "bold",color = cmap[i], textcoords = "offset points")# 添加标题和排名序号#ax_base.set_title(title,color = "black",fontsize = 12)ax_base.text(0.5, 0.95, title, va="center", ha="center", size = 12,transform = ax_base.transAxes)ax_base.text(0.5, 0.5, text, va="center", ha="center", alpha=0.3, size = 50,transform = ax_base.transAxes)# 添加注意力动画if m==0:px,py,pz = dfdata["x"][[-1]],dfdata["y"][[-1]],dfdata["z"][-1]p = dfdata.index[-1]+":"+str(pz//10000)+"万"ax_base.scatter(px,py,s = 800*pz/df["z"].mean(),c = cmap[len(dfdata)-1:len(dfdata)],alpha = 0.5,zorder = 4)ax_base.annotate(p,xy = (px,py),  xycoords = "data",xytext = (-15,10),fontsize = 20,fontweight = "bold",color = cmap[k-1], textcoords = "offset points",zorder = 5)if m==1:px,py,pz = dfdata["x"][[-1]],dfdata["y"][[-1]],dfdata["z"][-1]p = dfdata.index[-1]+":"+str(pz//10000)+"万"ax_base.scatter(px,py,s = 400*pz/df["z"].mean(),c = cmap[len(dfdata)-1:len(dfdata)],alpha = 0.5,zorder = 4)ax_base.annotate(p,xy = (px,py),  xycoords = "data",xytext = (-15,10),fontsize = 15,fontweight = "bold",color = cmap[k-1], textcoords = "offset points",zorder = 5)if m==2:px,py,pz = dfdata["x"][[-1]],dfdata["y"][[-1]],dfdata["z"][-1]p = dfdata.index[-1]+":"+str(pz//10000)+"万"ax_base.scatter(px,py,s = 100*pz/df["z"].mean(),c = cmap[len(dfdata)-1:len(dfdata)],alpha = 0.5,zorder = 4)ax_base.annotate(p,xy = (px,py),  xycoords = "data",xytext = (-15,10),fontsize = 10,fontweight = "bold",color = cmap[k-1], textcoords = "offset points",zorder = 5)my_animation = animation.FuncAnimation(fig,plot_frame,frames = range(0,3*len(df)),interval = int(duration*1000))if filename is None:try:from IPython.display import HTMLHTML(my_animation.to_jshtml())return HTML(my_animation.to_jshtml())except ImportError:passelse:my_animation.save(filename)return filenamehtml_file = "中国超500万人口城市.html"
bubble_map_dance(df,filename = html_file)gif_file = html_file.replace(".html",".gif")
html_to_gif(html_file,gif_file,duration=0.5)

收工。????

万水千山总是情,点个在看行不行?????

这篇关于中国88个超500万人口的大中城市都在哪里?Python动态图告诉你!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/286473

相关文章

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑