在ggplot2中向散点图添加水平线

时间:2019-03-24 23:22:17

标签: r ggplot2 geom-hline

此后 How to add the results of applying a function to an existing data frame?

library (tidyverse)
library (epitools)


# here's my made up data

DISEASE = c("Marco Polio","Marco Polio","Marco Polio","Marco Polio","Marco Polio",
            "Mumps","Mumps","Mumps","Mumps","Mumps",
            "Chicky Pox","Chicky Pox","Chicky Pox","Chicky Pox","Chicky Pox")
YEAR = c(2011, 2012, 2013, 2014, 2015,
         2011, 2012, 2013, 2014, 2015,
         2011, 2012, 2013, 2014, 2015)
VALUE = c(82,89,79,51,51,
          79,91,69,89,78,
          71,69,95,61,87)
AREA =c("A", "B","C")

DATA = data.frame(DISEASE, YEAR, VALUE,AREA)


DATA %>%
    mutate(POPN = case_when(
        AREA == "A" ~ 2.5,
        AREA == "B" ~ 3,
        AREA == "C" ~ 7,
        TRUE ~ 0)) %>%
    group_by(DISEASE,AREA,POPN) %>%
    count(AREA) %>%
    mutate(res = list(pois.byar(n, POPN))) %>%
    unnest()

给我我需要的东西。

我想做的是在散点图上画出一条水平线等于我计算出的比率之一的散点图。而不是手动添加。

我认为这可能有效

DATA%>%filter(DISEASE== "Chicky Pox")%>%
  ggplot(aes(x=AREA, y=rate)) +geom_point() +
  geom_hline(yintercept=20, linetype="dashed", color = "red")

这样做。 它给我20点的分界线。 但是,我怎样才能使我得到一条与区域A的费率值相等的线(例如)。 这样,您可以快速查看哪些速率高于或低于A速率。

再次。抱歉,这很简单。但是已经晚了...

1 个答案:

答案 0 :(得分:1)

您可以在aes()中放入一些简单的子集条件,这意味着只要条件不太复杂,这就非常简单:

DATA %>%
    filter(DISEASE== "Chicky Pox") %>%
    ggplot(aes(x=AREA, y=rate)) +
    geom_point() +
    geom_hline(aes(yintercept=rate[AREA == "A"]), 
               linetype="dashed", color = "red")