py 可视化图层

2024-08-28 23:36
文章标签 可视化 py 图层

本文主要是介绍py 可视化图层,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

五张图:数据资源可联系1493175691@qq.com

import numpy as np
import matplotlib.pyplot as plt
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io.shapereader import Reader
from matplotlib import pyplot as plt
from matplotlib.colors import LightSource, ListedColormap
from mpl_toolkits.axes_grid1 import make_axes_locatable
from osgeo import gdal
from osgeo import osr
from matplotlib import rcParams
config = {"font.family":'Times New Roman',"font.size":18,"mathtext.fontset":'stix'}
rcParams.update(config)
# 设置DEM路径
dem_file = r"..\2.DEM\裁剪\裁剪最后.tif"
# 使用GDAL驱动并读取DEM数据
ds = gdal.Open(dem_file)
tif_proj =ds.GetProjection()
tif_geotrans =ds.GetGeoTransform()
#确保TIFF的坐标系统信息
tif_crs = osr.SpatialReference(wkt=tif_proj)
# 读取TIFF数据到numpy数组
band = ds.GetRasterBand(1)
data = band.ReadAsArray()
# 设置无效值
nodata = ds.GetRasterBand(1).GetNoDataValue()
if np.any(data == nodata):data = np.ma.masked_equal(data, nodata)
ls=LightSource(azdeg=360,altdeg=30)
# 自定义色带
colors = ["#2B6743","#80A363","#F0EF9B","#C79F4B","#923100","#692610", "#470900"]
cmap = ListedColormap(colors)
rgb=ls.shade(data,cmap=cmap,blend_mode='overlay',vert_exag=2,dx=10,dy=10,fraction=1.05)
region=[-125, -67, 23, 50]
fig = plt.figure(figsize=(16,9))
ax = fig.add_subplot(111,projection=ccrs.PlateCarree())
proj=ccrs.PlateCarree()
ax.set_extent(region, crs = proj)
ax.stock_img()
extent=(tif_geotrans[0],tif_geotrans[0]+tif_geotrans[1]*data.shape[1],tif_geotrans[3]+tif_geotrans[5]*data.shape[0],tif_geotrans[3])
img = ax.imshow(rgb,aspect='auto',origin='upper',cmap=cmap,extent=extent,transform=ccrs.PlateCarree())
# 设置colorbar
img2 = ax.imshow(data,cmap=cmap)
cbar=plt.colorbar(img2,shrink=0.85,orientation='vertical',extend='both',pad=0.01,aspect=30)
cbar.set_label('DEM/m')
cbar.ax.tick_params(labelsize=12, direction='in', right=False)
ax.set_xticks(np.arange(region[0], region[1] + 1, 10), crs = proj)
ax.set_yticks(np.arange(region[-2], region[-1] + 1, 10), crs = proj)
ax.xaxis.set_major_formatter(LongitudeFormatter(zero_direction_label=False))
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.add_geometries(Reader(r'..\原始‘数据\美国西海岸shp\USA.shp').geometries(),ccrs.PlateCarree(),facecolor='none',edgecolor='white',linewidth=0.4)
# ax.add_geometries(Reader(r'E:\work\2024年\Wecaht2\南大\Aug28\python\投影坐标系shp\投影坐标系shp.shp').geometries(),ccrs.PlateCarree(),facecolor='none',edgecolor='black',linewidth=2)ax.set_title('立体DEM地形图',{'family':'simhei','size':18,'color':'k'})
plt.savefig('./地形图.png',dpi=200,bbox_inches='tight',pad_inches=0)
plt.show()

import geopandas as gpd
import matplotlib.pyplot as plt# 读取 shapefile 文件
shapefile_path = r'..\投影坐标系shp\投影坐标系shp.shp'  # 替换为你的shapefile路径
gdf = gpd.read_file(shapefile_path)# 确保你的shapefile中有表示大小的数据列,例如'population'或其他数值字段
# 此字段将用于控制圆形的大小
size_column = 'Shape_Leng'  # 替换为你数据中用于定义大小的字段名# 创建一个较小的图,显示区域边界
fig, ax = plt.subplots(figsize=(10, 6))  # 将图的大小调整为 10x6 英寸
gdf.boundary.plot(ax=ax, linewidth=1, color="gray")# 获取每个区域的中心点,用于绘制气泡图
gdf['coords'] = gdf['geometry'].apply(lambda x: x.representative_point().coords[:])
gdf['coords'] = [coords[0] for coords in gdf['coords']]# 根据 size_column 的值确定气泡大小
# 调整 scale_factor 以适应气泡的大小
scale_factor = 10000  # 该值可以调整,适应你的数据
gdf.plot(ax=ax, color='none', edgecolor='gray')
plt.scatter(x=[point[0] for point in gdf['coords']],y=[point[1] for point in gdf['coords']],s=gdf[size_column] / scale_factor,  # 调整s参数以控制气泡大小color='blue', alpha=0.5, edgecolor='white')# 去除坐标轴
ax.set_axis_off()# 设置标题
plt.title("Map with Proportional Symbols", fontsize=15)
plt.savefig('./比例符号图.png',dpi=200,bbox_inches='tight',pad_inches=0)
# 我使用的是各个县的周长数据,巧妇难为无米之炊啊# 显示图像
plt.show()

import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib import rcParamsconfig = {"font.family":'Times New Roman',"font.size":12,"mathtext.fontset":'stix'}
rcParams.update(config)# 读取 shapefile 文件
shapefile_path = r'..\投影坐标系shp\投影坐标系shp.shp' # 替换为你的shapefile路径
gdf = gpd.read_file(shapefile_path)# 检查数据是否加载正确
print(gdf.head())
fig, ax = plt.subplots(1, 1, figsize=(10, 8))# 可视化 Shape_Area 字段
gdf.plot(column='Shape_Area', cmap='viridis', legend=True,legend_kwds={'label': "Area by Shape_Area(m²)",'orientation': "horizontal"},edgecolor='white', linewidth=0.3, ax=ax)# 设置标题和显示
plt.title("Area heat map of counties in the United States")
plt.savefig('./面积图.png',dpi=600,bbox_inches='tight',pad_inches=0)
plt.show()

# # -*- coding: utf-8 -*-
# """
# Created on Mon Jun  1 08:07:10 2020
# @author: cbq
# """
#
# import os
# from pyecharts import options as opts
# from pyecharts.charts import Geo
# from pyecharts.globals import ChartType, SymbolType
#
# # 手动定义一些美国主要城市的经纬度坐标
# city_coordinates = {
#     "Los Angeles": [-118.2437, 34.0522],
#     "New York": [-74.0060, 40.7128],
#     "Chicago": [-87.6298, 41.8781],
#     "Houston": [-95.3698, 29.7604],
#     "Phoenix": [-112.0740, 33.4484],
# }
#
# # 创建 Geo 对象
# geo = Geo()
#
# # 添加美国地图
# geo.add_schema(
#     maptype="world",  # 改为 "world" 测试地图是否正常加载,"USA" 是目标地图
#     itemstyle_opts=opts.ItemStyleOpts(color="#323c48", border_color="#111"),
# )
#
# # 手动添加城市坐标
# for city, coord in city_coordinates.items():
#     geo.add_coordinate(city, coord[0], coord[1])
#
# # 添加城市和路径数据
# geo.add(
#     "Cities",
#     [("Los Angeles", 55), ("New York", 66), ("Chicago", 77), ("Houston", 88), ("Phoenix", 42)],
#     type_=ChartType.EFFECT_SCATTER,
#     color="white",
# )
#
# geo.add(
#     "Migration Path 1",
#     [("Los Angeles", "New York"), ("Los Angeles", "Chicago"), ("Los Angeles", "Houston")],
#     type_=ChartType.LINES,
#     effect_opts=opts.EffectOpts(
#         symbol=SymbolType.ARROW, symbol_size=6, color="blue"
#     ),
#     linestyle_opts=opts.LineStyleOpts(curve=0.2),
# )
#
# geo.add(
#     "Migration Path 2",
#     [("Phoenix", "Chicago"), ("Phoenix", "Houston"), ("Chicago", "New York")],
#     type_=ChartType.LINES,
#     effect_opts=opts.EffectOpts(
#         symbol=SymbolType.ARROW, symbol_size=8, color="yellow"
#     ),
#     linestyle_opts=opts.LineStyleOpts(curve=0.2),
# )
#
# geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
# geo.set_global_opts(title_opts=opts.TitleOpts(title="Geo-Lines-background"))
#
# # 渲染并生成 HTML 文件
# geo.render("geo_lines_background.html")
#
# # 自动打开生成的HTML文件
# os.system("start geo_lines_background.html")import geopandas as gpd
import matplotlib.pyplot as plt# 读取shapefile文件
gdf = gpd.read_file(r'..\原始‘数据\美国西海岸shp\USA.shp')# 绘制地图
fig, ax = plt.subplots(figsize=(10, 6))
gdf.boundary.plot(ax=ax, linewidth=1, color="gray")# 添加点和箭头
points = [{"name": "Los Angeles", "coord": (-118.2437, 34.0522), "dx": 5, "dy": 2, "color": "blue"},{"name": "Phoenix", "coord": (-112.0740, 33.4484), "dx": 2, "dy": 3, "color": "red"},{"name": "San Francisco", "coord": (-122.4194, 37.7749), "dx": 3, "dy": -1, "color": "green"},{"name": "Las Vegas", "coord": (-115.1398, 36.1699), "dx": -1, "dy": 4, "color": "purple"},
]# 绘制点和箭头
for point in points:ax.plot(point["coord"][0], point["coord"][1], 'o', color=point["color"], markersize=10)ax.text(point["coord"][0], point["coord"][1], point["name"], fontsize=12, ha='right')ax.arrow(point["coord"][0], point["coord"][1], point["dx"], point["dy"],head_width=0.5, head_length=1, fc=point["color"], ec=point["color"])# 保存为图片
plt.title("migration map", fontsize=15)
plt.savefig('migration_map.png',dpi=600)# 显示地图
plt.show()

 

import rasterio
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm# 读取土地利用分类数据 (tif文件)
tif_path = r'普通版裁剪.tif'
with rasterio.open(tif_path) as src:landuse = src.read(1)  # 读取第一个波段# 检查数据中的唯一值
unique_values = np.unique(landuse)
print(f"Unique values in the dataset: {unique_values}")# 假设红色背景的值是230,可以掩盖这些值
# 如果其他值是背景色,可以在这里添加掩盖条件
landuse = np.ma.masked_where(landuse == 32767, landuse)# 定义颜色映射(根据ArcGIS中的显示效果)
colors = ['#C8C8C8', '#C8C864', '#00FF00', '#00A000', '#006400',  # 10, 11, 30, 40, 50'#FFFF00', '#A0A000', '#00A0A0', '#0080FF', '#0000FF',  # 60, 61, 70, 71, 80'#A000FF', '#FF00FF', '#FF00A0', '#A00000', '#FF0000',  # 90, 100, 110, 120, 130'#FF8000', '#FFA000', '#FFD000', '#FF0000', '#008000',  # 140, 150, 152, 160, 170'#804000', '#00A0FF', '#808000', '#C0C000', '#FF0000'   # 180, 190, 200, 210, 220
]
cmap = ListedColormap(colors)# 定义分类边界
boundaries = [10, 11, 30, 40, 50, 60, 61, 70, 71, 80,90, 100, 110, 120, 130, 140, 150, 152, 160, 170,180, 190, 200, 210, 220, 230
]
norm = BoundaryNorm(boundaries, cmap.N, clip=True)# 创建图形和轴
fig, ax = plt.subplots(figsize=(15, 10))# 显示土地利用分类数据
img = ax.imshow(landuse, cmap=cmap, norm=norm)# 创建颜色条(图例)
cbar = plt.colorbar(img, ax=ax, boundaries=boundaries, ticks=[i for i in boundaries])
cbar.ax.set_yticklabels([f'Class {i}' for i in boundaries])  # 根据实际分类调整# 设置标题
ax.set_title('Land Use Classification')# 移除坐标轴
ax.axis('off')
plt.savefig('migration_map.png',dpi=600)
# 显示图像
plt.show()

这篇关于py 可视化图层的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

使用Vue-ECharts实现数据可视化图表功能

《使用Vue-ECharts实现数据可视化图表功能》在前端开发中,经常会遇到需要展示数据可视化的需求,比如柱状图、折线图、饼图等,这类需求不仅要求我们准确地将数据呈现出来,还需要兼顾美观与交互体验,所... 目录前言为什么选择 vue-ECharts?1. 基于 ECharts,功能强大2. 更符合 Vue

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

Python 交互式可视化的利器Bokeh的使用

《Python交互式可视化的利器Bokeh的使用》Bokeh是一个专注于Web端交互式数据可视化的Python库,本文主要介绍了Python交互式可视化的利器Bokeh的使用,具有一定的参考价值,感... 目录1. Bokeh 简介1.1 为什么选择 Bokeh1.2 安装与环境配置2. Bokeh 基础2

一文带你搞懂Python中__init__.py到底是什么

《一文带你搞懂Python中__init__.py到底是什么》朋友们,今天我们来聊聊Python里一个低调却至关重要的文件——__init__.py,有些人可能听说过它是“包的标志”,也有人觉得它“没... 目录先搞懂 python 模块(module)Python 包(package)是啥?那么 __in

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1