Reputation: 4443
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):
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?
Upvotes: 0
Views: 109
Reputation: 43334
You can do most of the heavy lifting with geom_segment
:
library(ggplot2)
ggplot(data.frame(x = 1:5,
y = c(140, 165, 125, 175, 185)),
aes(x, y, xend = x, yend = 150, label = y - 150)) +
geom_point(color = 'seagreen') +
geom_hline(yintercept = 150, color = 'seagreen') +
geom_segment(linetype = 'dashed', color = 'seagreen') +
geom_text(nudge_x = .1)
Upvotes: 3
Reputation: 7153
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"))
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))
Upvotes: 2