这里可以使用ggplot的faceting吗?

Can ggplot's faceting be used here?

欢迎来到 Tidyville。

下面是一个小 df,显示了 Tidyville 的城市人口。有些城市属于 A 州,有些城市属于 B 州。

我想用红色突出显示人口减少的城市。至此任务完成。

但是 Tidyville 有很多州。有没有办法使用 ggplot 的 faceting faceting 来显示每个州的情节。我不确定,因为我是新手,我在 ggplot 调用之外做了一些计算,以确定人口减少的城市。

library(ggplot2)
library(tibble)

t1 <- tibble (
  y2001 = c(3, 4, 5, 6, 7, 8, 9, 10),
  y2016 = c(6, 3, 9, 2, 8, 2, 11, 15),
  type = c("A", "A", "B", "B", "A", "A", "B", "B")
)

years <-  15
y2001 <- t1$y2001
y2016 <- t1$y2016

# Places where 2016 pop'n < 2001 pop'n
yd <- y2016 < y2001

decrease <- tibble (
  y2001 = t1$y2001[yd],
  y2016 = t1$y2016[yd]
)

# Places where 2016 pop'n >= 2001 pop'n
yi <- !yd

increase <- tibble (
  y2001 = t1$y2001[yi],
  y2016 = t1$y2016[yi]
)

ggplot() + 
  # Decreasing
  geom_segment(data = decrease, aes(x = 0, xend = years, y = y2001, yend = y2016), 
             color = "red") +

  # Increasing or equal
  geom_segment(data = increase, aes(x = 0, xend = years, y = y2001, yend = y2016), 
             color = "black") 

我相信你不需要创建两个新的数据集,你可以添加一列到 t1

t2 <- t1
t2$decr <- factor(yd + 0L, labels = c("increase", "decrease"))

我保留了原件 t1 并更改了副本,t2
现在为了应用 ggplot 个方面,也许这就是您要找的东西。

ggplot() + 
  geom_segment(data = t2, aes(x = 0, xend = years, y = y2001, yend = y2016), color = "red") +
  facet_wrap(~ decr)

如果要更改颜色,请使用新列 decr 作为值 color。请注意,此参数改变了它的位置,现在是 aes(..., color = decr).

ggplot() + 
  geom_segment(data = t2, aes(x = 0, xend = years, y = y2001, yend = y2016, color = decr)) +
  facet_wrap(~ decr)

您的中间步骤是不必要的,并且会丢失一些数据。我们将保留您首先创建的内容:

t1 <- tibble (
  y2001 = c(3, 4, 5, 6, 7, 8, 9, 10),
  y2016 = c(6, 3, 9, 2, 8, 2, 11, 15),
  type = c("A", "A", "B", "B", "A", "A", "B", "B")
)
years <- 15

但是我们不会进行所有的分离和子集化,而是创建一个虚拟变量来表示是否 y2016 > y2001

t1$incr <- as.factor(ifelse(t1$y2016 >= t1$y2001, 1, 0))

然后我们可以将数据参数提取到 ggplot() 调用以提高效率。我们将只使用一个 geom_segment() 参数并将 color() 参数设置为我们之前创建的虚拟变量。然后我们需要将颜色向量传递给 scale_fill_manual()value 参数。最后,添加 facet_grid() 参数。如果您只对一个变量进行分面,则可以在波浪号的另一侧放置一个句点。句号在前意味着它们将被镶嵌 side-by-side,句号在最后意味着它们将被堆叠在每个 toher

之上
ggplot(data = t1) +
  geom_segment(aes(x = 0, xend = years, y = y2001, yend = y2016, color=incr)) +
  scale_fill_manual(values=c("black", "red")) +
  facet_grid(type~.)

我认为,如果您将数据以 ggplot2 期望的整洁格式放置,这会容易得多。这是使用 tidyverse 函数的可能解决方案

library(tidyverse)
t1 %>% 
  rowid_to_column("city") %>% 
  mutate(change=if_else(y2016 < y2001, "decrease", "increase")) %>% 
  gather(year, pop, y2001:y2016) %>%
  ggplot() + 
    geom_line(aes(year, pop, color=change, group=city)) +
    facet_wrap(~type) + 
    scale_color_manual(values=c("red","black"))

这导致

require(dplyr)
t1<-mutate(t1,decrease=y2016<y2001)
ggplot(t1)+facet_wrap(~type)+geom_segment(aes(x = 0, xend = years, y = y2001, yend = y2016, colour=decrease))