Reputation: 1664
require(reshape2);require(ggplot2)
df <- data.frame(time = 1:10,
x1 = rnorm(10),
x2 = rnorm(10),
x3 = rnorm(10),
y1 = rnorm(10),
y2 = rnorm(10))
df <- melt(df, id = "time")
ggplot(df, aes(x = time, y = value, color = variable, group = variable,
size = variable, linetype = variable)) +
geom_line() +
scale_linetype_manual(values = c(rep(1, 3), 2, 2)) +
scale_size_manual(values = c(rep(.3, 3), 2, 2)) +
scale_color_manual(values = c(rep("grey", 3), "red", "green")) +
theme_minimal()
This example might not be very representative, but, for example, imagine running bunch of regression models that individually are not important but just contribute to the picture. While I want to emphasize only actual and averaged fit series. So basically variables x are not important and should not appear on legend.
I've tried to set scale_color_discrete(breaks = c("y1", "y2"))
as suggested in some other posts. But the problem is that all of aesthetics are already in use via manual and trying to set another discrete version will override properties that are already set for graph (and mess up whole thing). So ideally - I'd want to see the exact same graph, but only y1 and y2 displayed in the legend.
Upvotes: 2
Views: 759
Reputation: 128
You can try subsetting the data set by the variable name and plotting them separately.
p <- ggplot(df, aes(x = time, y = value, color = variable,
group = variable, size = variable, linetype = variable)) +
geom_line(data=df[which(substr(df$variable,1,1)=='y'),])+
scale_linetype_manual(values = c(2, 2)) + scale_size_manual(values = c(2, 2)) +
scale_color_manual(values = c("red", "green")) +
theme_minimal() +
geom_line(data=df[which(substr(df$variable,1,1)=='x'),],
aes(x = time, y = value, group = variable),
color="grey",size=0.3,linetype=1)
# Plot elements that have attributes set outside of aes() will
# not appear on legend!
Upvotes: 1