Customizing legend text and colors in ggplot2
I am trying to get a plot (using ggplot) that will plot geom_point
and geom_line
where different variables are plotted in different colors (according to scale_colour_manual(value = color)
where color
is a custom array of colors) in addition to two horizontal black lines (geom_hline
).
My trouble arises when I attempt to get the legend text for the horizontal lines customized. It appears that I can have only one of the two:
- the color of the horizontal line as black but the legend text for this line is incorrect
- the legend text for this line is correct but the color of the horizontal line is determined by the aforementioned
scale_colour_manual
color.
plot <- ggplot(data, aes(x = factor(Month), y = avgLoss, colour = type, order = -as.numeric(type)))
+ geom_line() + geom_point()
meanplus2sd <- mean(data$avgLoss) + 2*sd(data$avgLoss)
plot <- plot + geom_hline(aes(yintercept = meanplus2sd), colour = "black")
produces black line that开发者_开发问答 says "black" in the legend
plot <- plot + geom_hline(aes(yintercept = meanplus2sd, colour = "Mean + 2 Stdev."))
produces a line that is the next color in my defined scale_colour_manual
array, but the legend text is "Mean + 2 Stdev."
Any help in getting both custom color and legend text for a horizontal line in addition to the standard geom_point + geom_line
plotting would be excellent. Thanks.
One way to get what you want would be to include the data for your horizontal black line in the original data frame. You example isn't exactly reproducible, so this may not be exactly the code you want, but this is the general idea:
Add rows to 'data', one for each level of 'Month', where the value of 'avgLoss' in each row is equal to 'meanplus2sd'. You'll probably want all the other columns to contain NAs. So,
newData <- head(data,length(unique(data$Month)))
newData$Month <- unique(data$Month)
newData$avgLoss <- rep(meanplus2sd,length(unique(data$Month)
newData$type <- rep('Mean + 2sd',length(unique(data$Month)))
#Then set all other values in newData to NA...and,
data <- rbind(data,newData)
That should get you started, you'll just have to make sure that the color "black" is in the right position in scale_colour_manual, which may take some fiddling.
Annotate might be a good option
x <- baseball
tmp <- subset(x, team == c("CHN","NYA"))
cols <- c("8" = "red","4" = "blue","6" = "darkgreen")
meanplus2sd <- mean(tmp$rbi) + 2*sd(tmp$rbi)
plot <- ggplot(tmp, aes(x = year, y = rbi, color = factor(team), order = -as.numeric(team))) +
geom_line() + geom_point() + geom_hline(aes(yintercept = meanplus2sd)) +
annotate("text",label="Mean + 2sd",x=min(tmp$year)+10, y=meanplus2sd+10)
精彩评论