中国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

相关文章

创新、引领、发展——SAMPE中国2024年会在京盛大开幕

绿树阴浓夏日长,在这个色彩缤纷的季节,SAMPE中国2024年会暨第十九届国际先进复合材料制品原材料、工装及工程应用展览会在中国国际展览中心(北京朝阳馆)隆重开幕。新老朋友共聚一堂,把酒话桑麻。 为期4天的国际学术会议以“先进复合材料,引领产业创新与可持续化发展”为主题,设立了34个主题分会场,其中包括了可持续化会场、国际大学生会场、中法复合材料制造技术峰会三个国际会场和女科技工作者委员会沙龙,

Python 字符串占位

在Python中,可以使用字符串的格式化方法来实现字符串的占位。常见的方法有百分号操作符 % 以及 str.format() 方法 百分号操作符 % name = "张三"age = 20message = "我叫%s,今年%d岁。" % (name, age)print(message) # 我叫张三,今年20岁。 str.format() 方法 name = "张三"age

一道经典Python程序样例带你飞速掌握Python的字典和列表

Python中的列表(list)和字典(dict)是两种常用的数据结构,它们在数据组织和存储方面有很大的不同。 列表(List) 列表是Python中的一种有序集合,可以随时添加和删除其中的元素。列表中的元素可以是任何数据类型,包括数字、字符串、其他列表等。列表使用方括号[]表示,元素之间用逗号,分隔。 定义和使用 # 定义一个列表 fruits = ['apple', 'banana

Python应用开发——30天学习Streamlit Python包进行APP的构建(9)

st.area_chart 显示区域图。 这是围绕 st.altair_chart 的语法糖。主要区别在于该命令使用数据自身的列和指数来计算图表的 Altair 规格。因此,在许多 "只需绘制此图 "的情况下,该命令更易于使用,但可定制性较差。 如果 st.area_chart 无法正确猜测数据规格,请尝试使用 st.altair_chart 指定所需的图表。 Function signa

python实现最简单循环神经网络(RNNs)

Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以向量的形式进行表示。 绿色部分是隐藏向量。是加工处理过程。 蓝色部分是输出向量。 python代码表示如下: rnn = RNN()y = rnn.step(x) # x为输入向量,y为输出向量 RNNs神经网络由神经元组成, python

python 喷泉码

因为要完成毕业设计,毕业设计做的是数据分发与传输的东西。在网络中数据容易丢失,所以我用fountain code做所发送数据包的数据恢复。fountain code属于有限域编码的一部分,有很广泛的应用。 我们日常生活中使用的二维码,就用到foutain code做数据恢复。你遮住二维码的四分之一,用手机的相机也照样能识别。你遮住的四分之一就相当于丢失的数据包。 为了实现并理解foutain

python 点滴学

1 python 里面tuple是无法改变的 tuple = (1,),计算tuple里面只有一个元素,也要加上逗号 2  1 毕业论文改 2 leetcode第一题做出来

Python爬虫-贝壳新房

前言 本文是该专栏的第32篇,后面会持续分享python爬虫干货知识,记得关注。 本文以某房网为例,如下图所示,采集对应城市的新房房源数据。具体实现思路和详细逻辑,笔者将在正文结合完整代码进行详细介绍。接下来,跟着笔者直接往下看正文详细内容。(附带完整代码) 正文 地址:aHR0cHM6Ly93aC5mYW5nLmtlLmNvbS9sb3VwYW4v 目标:采集对应城市的

python 在pycharm下能导入外面的模块,到terminal下就不能导入

项目结构如下,在ic2ctw.py 中导入util,在pycharm下不报错,但是到terminal下运行报错  File "deal_data/ic2ctw.py", line 3, in <module>     import util 解决方案: 暂时方案:在终端下:export PYTHONPATH=/Users/fujingling/PycharmProjects/PSENe

将一维机械振动信号构造为训练集和测试集(Python)

从如下链接中下载轴承数据集。 https://www.sciencedirect.com/science/article/pii/S2352340918314124 import numpy as npimport scipy.io as sioimport matplotlib.pyplot as pltimport statistics as statsimport pandas