Reputation: 189
I want to add two vertical line and two horizontal line to existing ggplot with legend.
I have tried this:
library(ggplot2)
x <- c(1:70)
y <- c((1:70)^2)
df <- data.frame(x,y)
ggplot(df, aes(x = x, y = y)) +
ylab(expression(bold("Height"))) +
xlab(expression(bold("Width"))) +
geom_point(size=1, col="red") +
geom_hline(aes(yintercept=2000, linetype = "1st border of height"),col="green",size=1) +
geom_hline(aes(yintercept=4000, linetype = "2st border of height"), col="red", size=1) +
geom_vline(aes(xintercept=20, linetype = "1st border of width"), col="blue", size=1, linetype="dashed") +
geom_vline(aes(xintercept=40, linetype = "2st border of width"),col="darkblue", size=1, linetype="dashed") +
geom_smooth(lwd=1, col="blue", span = 0.8, se=F) +
scale_linetype_manual(name = "Legend", values = c(1,2,1,1),
guide = guide_legend(override.aes = list(color = c("green", "red", "blue", "darkblue")))) +
theme()
Can somebody help me?
Upvotes: 1
Views: 338
Reputation: 17648
You can try
x <- c(1:70)
y <- c((1:70)^2)
df <- data.frame(x,y)
df_lines <- data.frame(type = factor(rep(c("yintercept", "xintercept"), each = 2)), y = c(2000, 4000, 20, 40), border_of_height = as.character(1:2))
ggplot(df, aes(x = x, y = y)) +
ylab(expression(bold("Height"))) +
xlab(expression(bold("Width"))) +
geom_point(size=1, col="red") +
geom_smooth(lwd=1, col="blue", span = 0.8, se=F) +
geom_hline(data = df_lines[1:2, ], aes(yintercept = y, color = border_of_height, linetype = type)) +
geom_vline(data = df_lines[3:4, ], aes(xintercept = y, color = border_of_height, linetype = type), show.legend = F)
Upvotes: 1