【问题标题】:Change Visual Order of Overlapping Factor Values in geom_sf in R更改 R 中 geom_sf 中重叠因子值的视觉顺序
【发布时间】:2020-02-16 22:16:20
【问题描述】:

(加载库)

library(tidyverse)
library(sf)

假设我们有两个点在同一位置 (x,y) 但具有不同的值 (z):

x<-c(1,1)
y<-c(1,1)
z<-c(0,1)

我知道 geom_point 会根据数据集的顺序更改显示值的顺序(位于顶部):

ggplot(data=points, aes(x=x,y=y))+geom_point(aes(color=z),size=20)
ggplot(data=points%>%arrange(desc(z)), aes(x=x,y=y))+geom_point(aes(color=z),size=20)

order 1 order 2

如果“z”是一个因素,这仍然有效。

如果我将点放入 sf 对象并使用 geom_sf 绘制它们,如果“z”是数字,它就可以工作。

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) )+geom_sf(aes(color=z),size=20)

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%arrange(desc(z)))+geom_sf(aes(color=z),size=20)

sf num order 1 sf num order 2

但是,使用 geom_sf 和 factor(z),当我重新排序数据集时没有任何变化。

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%mutate(z=factor(z)))+geom_sf(aes(color=z),size=20)

ggplot(data=points%>%st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%mutate(z=factor(z))%>%
arrange(desc(z)))+geom_sf(aes(color=z),size=20)

sf factor order 1 sf factor order 2

如何在上一个示例中强制重新排序?

非常感谢!

【问题讨论】:

    标签: r ggplot2 sf


    【解决方案1】:

    在您的最后一个示例中,您可以通过在将 z 设置为因子之前重新排列 z 的顺序并将 z 的唯一值归因于因子级别如下来强制重新排序:

    library(tidyverse)
    library(sf)
    
    points%>%
      st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%
      arrange(desc(z)) %>%
      mutate(z=factor(z, levels = unique(z))) %>% str()
    
    Classes ‘sf’ and 'data.frame':  2 obs. of  2 variables:
     $ z       : Factor w/ 2 levels "1","0": 1 2
     $ geometry:sfc_POINT of length 2; first list element:  'XY' num  1 1
     - attr(*, "sf_column")= chr "geometry"
     - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA
      ..- attr(*, "names")= chr "z"
    

    str 输出中,您可以看到现在因子水平组织良好(0 之前的 1)如果我们绘制它,您会得到预期的图:

    library(tidyverse)
    library(sf)
    ggplot(data=points%>%
             st_as_sf(x=.,coords=c("x","y"),crs=4326) %>%
             arrange(desc(z)) %>%
             mutate(z=factor(z, levels = unique(z))))+
      geom_sf(aes(color=z),size=20)
    

    它回答了你的问题吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 2015-03-11
      • 2014-08-28
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多