【问题标题】:ggplot and sf - category by colorggplot 和 sf - 按颜色分类
【发布时间】:2023-02-17 22:18:36
【问题描述】:

在绘制这个非常简单的sf多点特征时

gm.multipoints <- st_multipoint(rbind(
  c(0.1, 51.5),
  c(11.3, 44.4),
  c(-3.7, 40.4),
  c(2.3, 48.8)
))

df.attr <- data.frame(
  name = c('London', 'Bologna', 'Madrid', 'Paris'),
  temperature = c(21,31,29,25),
  language = c('English', 'Italian', 'Spanish', 'French')
)

gmsf.multipoint <- st_sf(df.attr,geometry = st_sfc(gm.multipoints,crs = 'EPSG:4326'))

ggplot作为

ggplot(gmsf.multipoint) +
  geom_sf(aes(color=name))

我得到的所有城市的颜色都与附图中的颜色相同。为什么每个城市的颜色都不一样?

【问题讨论】:

  • 因为 st_multipoint 就是它所说的由多个点组成的(一个单一的)特征。你想要的是每行一个不同的点。如果您查看数据框(按示例打印),您会看到重复的几何图形。

标签: r ggplot2 sf


【解决方案1】:

因为 st_multipoint 就是它所说的由多个点组成的(一个单一的)特征。你想要的是每行一个不同的点。如果您查看数据框(按示例打印),您会看到重复的几何图形。

使用以下功能,您将能够创建多个单独的点。

# build POINT list (not a MULTIPOINT) from multiples coordinates
# adapted from sf:::st_as_sf.data.frame
st_points <- function(x, y=NULL, dim="XYZ", crs=NA_crs_) {
  if(is.data.frame(x))
    x <- as.matrix(x)
  if(!is.null(y))
    x <- cbind(x,y)
  if(!is.matrix(x))
    stop("Need a matrix!")
  structure(sf:::points_rcpp(x, dim),
    n_empty = 0L, precision = 0, crs = sf:::make_crs(crs), bbox = structure(c(xmin = min(x[[1]],
      na.rm = TRUE), ymin = min(x[[2]], na.rm = TRUE),
      xmax = max(x[[1]], na.rm = TRUE), ymax = max(x[[2]],
        na.rm = TRUE)), class = "bbox"), class = c("sfc_POINT",
          "sfc"), names = NULL)
}

gm.multipoints <- st_points(rbind(
  c(0.1, 51.5),
  c(11.3, 44.4),
  c(-3.7, 40.4),
  c(2.3, 48.8)
))

# rest of your code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多