本文主要是介绍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 可视化图层的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!