使用值列

如何解决使用值列

我有一些GPS数据,每个点都分配了一个值(就像空气质量一样)。我可以绘制这些点(例如,用大叶草),然后将值映射到圆的大小,如下所示:

import pandas,numpy,folium
lat = numpy.random.uniform(45,45.01,250)
lon = numpy.random.uniform(3,3.02,250)
value = numpy.random.uniform(0,50,250)
df = pandas.DataFrame({'lat': lat,'lon': lon,'value': value})
mymap = folium.Map(location = [lat.mean(),lon.mean()],tiles="OpenStreetMap",zoom_start=14)
for elt in list(zip(df.lat,df.lon,df.value)):
    folium.Circle(elt[:2],color="blue",radius=elt[2]).add_to(mymap)
mymap.save('mymap.html')

enter image description here

我想处理这些数据,对其进行插值并创建一个shapefile作为输出,其中插值的多边形包含平均值,并显示高和低值区域(右侧的 fake 图片)。当然,多边形的极限将根据插值自动生成。

我该如何实现?因为我已经尝试在大叶草中使用HeatMap工具,但是它的设计是为了插值点的密度,而不是与每个点关联的值! 我希望它不会太复杂。谢谢, 注意:我使用叶草,但我对其他python库也没问题。

解决方法

我们可以将这些值作为权重馈送到大叶中的HeatMap(请参阅文档中的data参数)。

这是一个例子。我将方框下半部分的值除以5,以证明尽管数据点的密度相对均匀,但热图在图片的上半部分显然显示出更高的幅度:

import pandas as pd
import numpy as np
import folium
from folium.plugins import HeatMap
import matplotlib as mpl

# parameters
n = 250                     # number of points
lat0 = 40.7                 # coordinates will be generated uniformly with
lon0 = -73.9                # lat0 - eps <= lat < lat0 + eps
eps = 0.1                   # lon0 - eps <= lon < lon0 + eps
v_min,v_max = 0,100       # min,max values

# generating values
lat = np.random.uniform(lat0 - eps,lat0 + eps,n)
lon = np.random.uniform(lon0 - eps,lon0 + eps,n)
value = numpy.random.uniform(v_min,v_max,n)
df = pandas.DataFrame({'lat': lat,'lon': lon,'value': value})

# to demonstrate the effect of weights on the heatmap,# we'll divide values below the center of the box by K = 5
K = 5
df.loc[df['lat'] < lat0,'value'] /= K

# plotting the map,both the points themselves and the heatmap
m = folium.Map(location = [lat0,lon0],tiles="OpenStreetMap",zoom_start=11,width=400,height=400)
for elt in list(zip(df.lat,df.lon,df.value)):
    folium.Circle(elt[:2],color="white",radius=elt[2]).add_to(m)

# df.values used here is a (250,3) numpy.ndarray
# with (lat,lon,weight) for each data point
HeatMap(data=df.values,min_opacity=0.1).add_to(m)

m

输出:

heatmap


更新

这是一种略有不同的方法,不使用内置的HeatMaps(鉴于@agenis提到的https://github.com/python-visualization/folium/issues/1271,这可能是一个更好的选择)。

我们首先将数据转换为正方形网格,其中每个正方形的值是该单元格内原始数据点值的平均值(因此,它不取决于该单元格内点的数量,仅取决于它们的值)。

然后,我们可以通过在地图上绘制GeoJson多边形来可视化这些正方形。这是一个示例:

# define the size of the square
step = 0.02

# calculate values for the grid
x = df.copy()
x['lat'] = np.floor(x['lat'] / step) * step
x['lon'] = np.floor(x['lon'] / step) * step
x = x.groupby(['lat','lon'])['value'].mean()
x /= x.max()
x = x.reset_index()

# geo_json returns a single square
def geo_json(lat,value,step):
    cmap = mpl.cm.RdBu
    return {
      "type": "FeatureCollection","features": [
        {
          "type": "Feature","properties": {
            'color': 'white','weight': 1,'fillColor': mpl.colors.to_hex(cmap(value)),'fillOpacity': 0.5,},"geometry": {
            "type": "Polygon","coordinates": [[
                [lon,lat],[lon,lat + step],[lon + step,]]}}]}


# generating a map...
m = folium.Map(location=[lat0,height=400)

# ...with squares...
for _,xi in x.iterrows():
    folium.GeoJson(geo_json(xi['lat'],xi['lon'],xi['value'],step),lambda x: x['properties']).add_to(m)

# ...and the original points
for elt in list(zip(df.lat,radius=elt[2]).add_to(m)

m

输出:

grid


更新(2):

以下是使用griddata在网格上进行插值的版本:

import pandas as pd
import numpy as np
import folium
from scipy.interpolate import griddata

# parameters
n = 250                     # number of points
lat0 = 40.7
lon0 = -73.9
eps = 0.1
v_min,max values

# generating values
lat = np.random.normal(lat0,eps,n)
lon = np.random.normal(lon0,n)

# set up the grid
step = 0.02
xi,yi = np.meshgrid(
    np.arange(lat.min() - step/2,lat.max() + step/2,np.arange(lon.min() - step/2,lon.max() + step/2,)

# interpolate and normalize values
zi = griddata((lat,lon),(xi,yi),method='linear')
zi /= np.nanmax(zi)
g = np.stack([
    xi.flatten(),yi.flatten(),zi.flatten(),],axis=1)

# geo_json returns a single square
def geo_json(lat,"coordinates": [[
                [lon - step/2,lat - step/2],[lon - step/2,lat + step/2],[lon + step/2,zoom_start=9,height=400)

# ...with squares...
for gi in g:
    if ~np.isnan(gi[2]):
        folium.GeoJson(geo_json(gi[0],gi[1],gi[2],lambda x: x['properties']).add_to(m)

# ...and the original points
for elt in list(zip(lat,value)):
    folium.Circle(elt[:2],color='white',radius=elt[2]).add_to(m)

m

输出:

grid_interpolated

,

在我看来,您需要过滤数据,以便根据给定类别将其分为几组。使用这些点集,您便应该能够生成凸包。似乎有一些方法可以做到此目的-请参见此处的一些示例: Convex hull area in Python?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-