Reputation: 383
I am trying to add a key for lines i have added to an existing ggplot.
setup:
test.mat <- data.frame(matrix(nrow=32, ncol =3))
test.mat[,1] = rep(1:16,2)
test.mat[1:16,2] = as.character(rep("Cohort Alpha"),16)
test.mat[17:32,2] = as.character(rep("Factor Alpha"), 16)
test.mat[,3] = rnorm(32,0,1)
colnames(test.mat) = c("Window", "type", "value")
ggplot(test.mat, aes(x=Window, y=value, size = type)) +
geom_line(aes(colour = type, linetype = type)) +
scale_colour_manual("type", values = c("black", "steelblue")) +
scale_linetype_manual("type", values = c("solid", "solid")) +
scale_size_manual("type", values = c(0.8, 1.4), guide = "none") +
xlab("Quarter after alpha assessment") + ylab("t-statistics") + ggtitle("Panel Regression t-statistics") + theme_classic() +
theme(
text = element_text(family = "Times New Roman"),
plot.title = element_text(color = "black", size = 12, hjust = 0.5),
axis.title = element_text(size = 12),
legend.title = element_blank()) +
geom_hline(yintercept = 1.282 , color = "dark green") +
geom_hline(yintercept = 1.645 , color = "dark grey") +
geom_hline(yintercept = 2.326 , color = "grey")
i want the dark green line labelled as ' * ', I want the dark grey line labelled as ' ** ', and i want the grey line denoted ' *** '. I want these labels to appear in the legend.
Upvotes: 0
Views: 31
Reputation: 30474
You can use linetype
in geom_hline
in aes
so that these lines will be included in a legend. I changed scale_linetype_manual
so it would reflect the colors of the new legend lines. Is this what you had in mind?
library(ggplot2)
set.seed(1)
test.mat <- data.frame(matrix(nrow=32, ncol =3))
test.mat[,1] = rep(1:16,2)
test.mat[1:16,2] = as.character(rep("Cohort Alpha"),16)
test.mat[17:32,2] = as.character(rep("Factor Alpha"), 16)
test.mat[,3] = rnorm(32,0,1)
colnames(test.mat) = c("Window", "type", "value")
ggplot(test.mat, aes(x=Window, y=value, size = type)) +
geom_line(aes(colour = type)) +
scale_colour_manual("type", values = c("black", "steelblue")) +
scale_size_manual("type", values = c(0.8, 1.4), guide = "none") +
xlab("Quarter after alpha assessment") + ylab("t-statistics") + ggtitle("Panel Regression t-statistics") + theme_classic() +
theme(
text = element_text(family = "Times New Roman"),
plot.title = element_text(color = "black", size = 12, hjust = 0.5),
axis.title = element_text(size = 12),
legend.title = element_blank()) +
geom_hline(aes(linetype = "*", yintercept = 1.282), color = "dark green") +
geom_hline(aes(linetype = "**", yintercept = 1.645), color = "dark grey") +
geom_hline(aes(linetype = "***", yintercept = 2.326), color = "grey") +
scale_linetype_manual("sig", values = c("solid", "solid", "solid"),
guide = guide_legend(override.aes = list(color=c("dark green", "dark grey", "grey"))))
Upvotes: 1