0

我想突出显示最大、最小值和最高残差点。我能够独立创建所有这些。请参见下面的代码:

library(alr4)

library(tidyverse)

library(broom)

library(ggplot2)

modelUN <- lm(log(fertility) ~ log(ppgdp), data = UN11)

#For Max Fertility

UN11 %>% mutate(has_highest_fertility = fertility == max(fertility), has_lowest_fertility = fertility == min(fertility)) %>% ggplot(aes(x = ppgdp, y = fertility, color = has_highest_fertility)) + geom_point()

#For Min Fertility

UN11 %>% mutate(has_highest_fertility = fertility == max(fertility), has_lowest_fertility = fertility == min(fertility)) %>% ggplot(aes(x = ppgdp, y = fertility, color = has_lowest_fertility)) + geom_point()

同样,我可以提取残差并执行此操作。但我有兴趣在一个情节中完成所有这些。并想给他们贴上标签。所以最低生育率会有一个字符串,“最低生育率”等等。

4

1 回答 1

2

这是一个尝试:将 a 分配lbl给所有点,NA对于大多数点和对两个极端有意义的点。(这允许您拥有任意数量的标签。)

library(dplyr)
library(ggplot2)
mtcars %>%
  mutate(
    lbl = case_when(
      row_number() == which.min(hp) ~ "Lowest HP",
      row_number() == which.max(hp) ~ "Highest HP",
      TRUE ~ NA_character_
    )
  ) %>%
  ggplot(., aes(mpg, disp)) +
  geom_point(aes(color = !is.na(lbl))) +
  geom_text(aes(label = lbl), hjust = -0.2, na.rm = TRUE) +
  scale_color_discrete(guide = FALSE)

mtcars 的 ggplot2 突出显示并标记了最小和最大 HP

于 2020-09-20T04:08:51.893 回答