user3115933 user3115933 - 7 months ago 26
R Question

How to create this particular graph in R using ggplot2?

I am new to R and I am using R in RStudio. I recently came across this graph (please see image below) in an R book (although it did not explain how this graph was achieved):

R Graph

I want to replicate this graph with the following data:

Serial Number of observations (to appear on the x-axis): 1, 2, 3, 4, 5

Value for each observation: 140, 165, 125, 175, 185

Average Budget Value (will be the horizontal line in the graph): 150

How do I go about creating this graph?

Answer Source
dat <- data.frame(x = 1:5, val=c(140, 165, 125, 175, 185), mean=150)
dat <- dat %>% gather(var, budget, val:mean)

ggplot(dat, aes(x, budget, group=as.factor(x))) + 
    geom_line() + 
    geom_hline(yintercept=150) + 
    geom_point(data=dat %>% filter(var=="val"))

enter image description here

To insert in the difference between point and mean:

dat2 <- dat %>% 
        group_by(x) %>% 
        summarise(val=diff(budget)*-1, mean=mean(budget)

ggplot(dat, aes(x, budget, group=as.factor(x))) + 
    geom_line(linetype="dotted") + 
    geom_hline(yintercept=150) + 
    geom_point(data=dat %>% filter(var=="val")) + 
    geom_text(data=dat2, aes(x+.1, mean, label=val))

enter image description here