使用从管道创建的 ggplot 突出显示单个数据点

Highlighing individual data points with ggplot created from pipes

我们有这个简单的数据框:

data <- data.frame(ID = rep(c("a","b"), each = 500),
                   time = 1:500,
                val = rnorm(1000, mean=1, sd = 0.3))

我们有 2 个人的数据(ID == ab)。我们想对个体 b 的数据进行子集化,并使用 dplyrggplot2:

制作 valdata_point 的散点图
library(ggplot2)
library(dplyr)
data%>%
  filter(ID == "b")%>%
  mutate(data_point = c(1:500))%>%
  ggplot(.,)+
    geom_point(aes(x=data_point, y=val), size = 0.5)

现在假设我们要使单个数据点(比如第一个数据 point/row)比其余数据大,并且颜色不同。我们怎样才能从管道内部做到这一点,而不必在管道外部制作 object?

您可以在管道内创建两个变量,一个用于突出显示颜色,另一个用于其大小。

library(ggplot2)
library(dplyr)

data %>%
  filter(ID == "b") %>%
  mutate(data_point = 1:500) %>%
  mutate(highlight = data_point == 1,
         size = 0.5 + 10*highlight) %>%
  ggplot(aes(x = data_point, y = val)) +
  geom_point(aes(color = highlight, size = size), show.legend = FALSE) +
  scale_color_manual(values = c("black", "red"))

不创建这两个变量的另一种方法是将相同的逻辑应用于 geom_point 中的美学调用。

data %>%
  filter(ID == "b") %>%
  mutate(data_point = 1:500) %>%
  ggplot(aes(x = data_point, y = val)) +
  geom_point(aes(color = data_point == 1, 
                 size = 0.5 + 10*(data_point == 1)), 
             show.legend = FALSE) +
  scale_color_manual(values = c("black", "red"))

两种情况下的结果如下。

编辑

感谢@Allan Cameron 在 中指出:

You would only need a single new variable in the first version, then use scale_size

结果几乎相同,高亮点 size 有 0.5 的差异。

data %>%
  filter(ID == "b") %>%
  mutate(data_point = 1:500) %>%
  mutate(highlight = data_point == 1) %>%
  ggplot(aes(x = data_point, y = val)) +
  geom_point(aes(color = highlight, size = highlight), show.legend = FALSE) +
  scale_color_manual(values = c("black", "red")) +
  scale_size_manual(values = c(0.5, 10*highlight))

您可以在 mutate() 中创建另一列来处理磅值。在此示例中,sizing_point 是一个以 5 开头的向量,后跟数字 0.5 重复 nrow(.)-1 次,在本例中为 499 次。

 #multiple columns can be defined in mutate() separated by a comma
 data %>% 
      filter(ID == "b") %>%
      mutate(sizing_point = c(5,rep(0.5,nrow(.)-1)), data_point = c(1:500))%>%
      ggplot(.,)+
      geom_point(aes(x=data_point, y=val, size= sizing_point)

你当然可以强调不同的观点。假设您想要突出显示第 75 个点。这是一个示例,说明如何为该项目指定磅值。

  #repeats .05 74 times, followed by 5, then repeats 0.5 again to the end of the vector
  c(rep(0.5,74),5,rep(0.5,nrow(.)-75))

并为突出显示的点添加颜色:

data %>% 
  filter(ID == "b") %>%
  mutate(sizing_point = c(5,rep(0.5,nrow(.)-1)), data_point = c(1:500))%>%
  ggplot(.,)+ geom_point(aes(x=data_point, y=val, size= sizing_point, color=factor(sizing_point)))+
  scale_color_manual(values = c("black", "red"))