I need to be able to control line types and colors in a plot, but also to change the Legend title. I can do either, but I have not been able to figure out how to do both. First, set up the data.
lcols = cbbPalette[c(2,3,4,1)]
linetype = rep(c('solid', 'dashed'),2)
LegendTitle = "Treatment"
x=rep(1:10,4)
y=c(1*1:10, 0.5*1:10, 0.25*1:10, 0.125*1:10)
cohort = factor(rep(LETTERS[1:4], each = 10))
df1 <- data.frame(x=x, y = y, cohort = cohort)
I can control the line type and color as follows (The bold stuff is lines commented out):
p <- ggplot(df1, aes(x,y, group = cohort)) +
geom_line(aes(linetype = cohort, col = cohort)) +
scale_color_manual(values = lcols) +
scale_linetype_manual(values = linetype) +
theme(legend.position = c(.20, .65))# +
# scale_linetype_discrete(name = LegendTitle) +
# scale_color_discrete(name = LegendTitle)
p
or I can change the legend title:
p <- ggplot(df1, aes(x,y, group = cohort)) +
geom_line(aes(linetype = cohort, col = cohort)) +
# scale_color_manual(values = lcols) +
# scale_linetype_manual(values = linetype) +
theme(legend.position = c(.20, .65)) +
scale_linetype_discrete(name = LegendTitle) +
scale_color_discrete(name = LegendTitle)
p
But I can't do both together.
p <- ggplot(df1, aes(x,y, group = cohort)) +
geom_line(aes(linetype = cohort, col = cohort)) +
scale_color_manual(values = lcols) +
scale_linetype_manual(values = linetype) +
theme(legend.position = c(.20, .65)) +
scale_linetype_discrete(name = LegendTitle) +
scale_color_discrete(name = LegendTitle)
> Scale for 'linetype' is already present. Adding another scale for
'linetype', which will replace the existing scale.
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
p
There must be a more straightforward way to change the text of a legend than what I used in the second example above, but I have been unable to find it after working on this for half a day. Does anyone know how I can make this work? As always, thanks in advance for any help you can give me.
Larry Hunsicker