我在 R 中有一个 data.frame,它具有区域对的值。可以使用以下代码构造第一列:
region.1 <- c("SE", "SE", "SW", "S", "SW")
region.2 <- c("SW", "S", "SE", "SE", "SE")
x <- c(1,2,3,4,5)
y <- c(1,3,2,4,1)
df <- data.frame(x,y,region.1,region.2)
我想为每对区域绘制一个具有不同颜色的图,所以我尝试过
ggplot(data=df, aes(x=x, y=y))+
geom_point(size=5,aes(color=interaction(region.1,region.2)))
然而,一旦考虑了相同交互的排列,结果并不是我所期望的。
如图所示,例如有组 SW.SE 和 SE.SW。
我想问一下,我怎样才能以一种智能的方式制作没有排列的对组。
这里有两个dplyr
基于选项。两者都涉及对每个 (x,y) 对的两个区域的值进行排序。第一个用于mutate
粘贴排序的值,使用rowwise
. 第二个用于gather
制作单列区域,按 (x,y) 对排列,然后summarise
将区域粘贴在一起。
library(tidyverse)
region.1 <- c("SE", "SE", "SW", "S", "SW")
region.2 <- c("SW", "S", "SE", "SE", "SE")
x <- c(1,2,3,4,5)
y <- c(1,3,2,4,1)
df <- data.frame(x,y,region.1,region.2)
df_interact1 <- df %>%
mutate_if(is.factor, as.character) %>%
rowwise() %>%
mutate(interact = sort(c(region.1, region.2)) %>% paste(., collapse = ".")) %>%
ungroup()
df_interact1
#> # A tibble: 5 x 5
#> x y region.1 region.2 interact
#> <dbl> <dbl> <chr> <chr> <chr>
#> 1 1 1 SE SW SE.SW
#> 2 2 3 SE S S.SE
#> 3 3 2 SW SE SE.SW
#> 4 4 4 S SE S.SE
#> 5 5 1 SW SE SE.SW
ggplot(df_interact1, aes(x = x, y = y, color = interact)) +
geom_point(size = 5)
df_interact2 <- df %>%
gather(key = region, value = value, region.1, region.2) %>%
group_by(x, y) %>%
arrange(value) %>%
summarise(interact = paste(min(value), max(value), sep = ".")) %>%
ungroup()
df_interact2
#> # A tibble: 5 x 3
#> x y interact
#> <dbl> <dbl> <chr>
#> 1 1 1 SE.SW
#> 2 2 3 S.SE
#> 3 3 2 SE.SW
#> 4 4 4 S.SE
#> 5 5 1 SE.SW
ggplot(df_interact2, aes(x = x, y = y, color = interact)) +
geom_point(size = 5)
由reprex 包(v0.2.0)于 2018 年 5 月 22 日创建。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句