sym246
sym246

Reputation: 1866

Remove a single label from ggplot legend

Example code:

library(ggplot2)
library(RcppRoll)
library(reshape2)
test_data2=data.frame(dates2015 <- seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by="days"), runif(365,0,1), runif(365,1,2))
colnames(test_data2)=c("Date", "var1", "var2")

var1roll=roll_mean(test_data2$var1, 21)
var2roll=roll_mean(test_data2$var2, 21)
var1roll=c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,var1roll,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA)
var2roll=c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,var2roll,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA)

test_data3=data.frame(test_data2, var1roll, var2roll)

test_data_long3 <- melt(test_data3, id="Date")
colnames(test_data_long3)=c("Date", "Method", "value")

group.colors <- c("#F8766D","#00BFC4","black", "black")
ggplot(data=test_data_long3,aes(x=Date, y=value, colour=Method)) + geom_line()+
  scale_colour_manual(values=group.colors)

In the legend that is plotted, it contains 4 variables representing the 4 lines which are drawn. I'd like to remove the final label, so that I am left with 3 items in the legend being the pink, blue and a single black line. The black line can be called 'Average' and will reference to both lines on the plot. At the moment it is distinguishing between the two average lines, when in fact, I do not want that distinction.

Thanks

Upvotes: 2

Views: 2782

Answers (1)

alexwhan
alexwhan

Reputation: 16026

This is how I'd approach it - instead of having the raw and mean data in one data.frame, I'd have them separated into two.

test_data_long3_raw <- melt(test_data3[,1:3], id="Date")
test_data_long3_mean <- melt(test_data3[,c(1,4:5)], id="Date")

Then you can add a geom_line for each. Using colour = "mean" inside aes() gives you a legend entry, even though colour is not mapped to a variable.

ggplot(test_data_long3_raw, aes(Date, value)) + geom_line(aes(colour = variable)) +
  geom_line(data = test_data_long3_mean, aes(group = variable, colour = "mean")) +
  scale_color_manual(values = c("black", "#F8766D","#00BFC4"))

enter image description here

Upvotes: 3

Related Questions