gpt4 book ai didi

r - 用 ggplot 填充 voronoi 多边形

转载 作者:行者123 更新时间:2023-12-04 18:34:29 26 4
gpt4 key购买 nike

我想用基于变量(在我的例子中为 z)的颜色填充 voronoi 多边形。这是代码:

library(rgdal)
library(deldir)
library(dplyr)
library(ggplot2)
library(UScensus2010)

x<-c(0,55,105,165,270,65,130,155,155,225,250,295,
30,100,110,135,160,190,230,300,30,70,105,170,
210,245,300,0,85,175,300,15,60,90,90,140,210,
260,270,295,5,55,55,90,100,140,190,255,285,270)
y<-c(305,310,305,310,310,260,255,265,285,280,250,
260,210,240,225,225,225,230,210,215,160,190,
190,175,160,160,170,120,135,115,110,85,90,90,
55,55,90,85,50,50,25,30,5,35,15,0,40,20,5,150)
z<-c(870,793,755,690,800,800,730,728,710,780,804,
855,813,762,765,740,765,760,790,820,855,812,
773,812,827,805,840,890,820,873,875,873,865,
841,862,908,855,850,882,910,940,915,890,880,
870,880,960,890,860,830)
dati<-data.frame(x,y,z)

vor_pts <- SpatialPointsDataFrame(cbind(dati$x,dati$y),dati, match.ID=TRUE)

SPointsDF_to_voronoi_SPolysDF <- function(sp) {

# tile.list extracts the polygon data from the deldir computation
vor_desc <- tile.list(deldir(sp@coords[,1], sp@coords[,2]))

lapply(1:(length(vor_desc)), function(i) {

# tile.list gets us the points for the polygons but we
# still have to close them, hence the need for the rbind
tmp <- cbind(vor_desc[[i]]$x, vor_desc[[i]]$y)
tmp <- rbind(tmp, tmp[1,])

# now we can make the Polygon(s)
Polygons(list(Polygon(tmp)), ID=i)

}) -> vor_polygons

# hopefully the caller passed in good metadata!
sp_dat <- sp@data

# this way the IDs _should_ match up w/the data & voronoi polys
rownames(sp_dat) <- sapply(slot(SpatialPolygons(vor_polygons),
'polygons'),
slot, 'ID')

SpatialPolygonsDataFrame(SpatialPolygons(vor_polygons),
data=sp_dat)

}

vor <- SPointsDF_to_voronoi_SPolysDF(vor_pts)

vor_df <- fortify(vor)


ggplot() +
geom_point(data = dati, aes(x, y), shape=21,
color = "white", fill = "steel blue") +
geom_map(data = vor_df, map = vor_df, aes(x = long, y = lat, map_id = id),
color = "#a5a5a5", fill = "#FFFFFF00", size = 0.25)

现在我有这张图片:

enter image description here

我希望每个多边形都应该根据变量 z 的值映射到一个颜色比例......我该怎么做?谢谢!!!

最佳答案

据我所知,您不能使用与数据问题本身长度不同的向量(在这种情况下是 vor_df 中的行数)来指定填充颜色。但是,如果我假设来自 z 的每个元素将应用于来自 vor_df 的形状的 id ,你可以这样做;

ggplot() +
geom_map(data=vor_df, map=vor_df,aes(x=long, y=lat, map_id=id, fill = id), size=0.25) +
geom_path(data=vor_df,aes(x=long, y=lat, map=id)) +
geom_point(data = dati, aes(x, y),shape=21, color="white", fill="steelblue")

enter image description here

这映射了 id列到每个多边形作为颜色。添加一个单独的列以根据向量 z 为每个 id 添加一个值应该很容易。如果您在图例或任何其他事物中需要它。

尽管如此,这都是基于每个 id 的假设。与向量 z 中的数字直接相关.

关于r - 用 ggplot 填充 voronoi 多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36108812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com