简体   繁体   中英

Adding a legend to ggplot with facet_grid

I am creating a 3x3 faceted graph using the code shown below. The problem is I get no legend.

# Create column vectors
XID <- rep(c(1,5,10), each=57)
TAD.unit <- c(0, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 10, 12, 16, 20, 24, 36, 48, 72)
TAD <- rep(TAD.unit, length=length(XID))
FID <-rep(c(1,2,3),each=length(TAD.unit),length=length(XID))
time <- TAD + (FID-1)*14*24
dist1 <- pweibull(TAD,2,2)
dist2 <- pweibull(TAD,2,4)

# Create data frame
data.df <- as.data.frame(cbind(XID,time, FID, dist1, dist2, TAD))

library(ggplot2)
label_both = function(column,value){paste(column,"=",value)}

# Create plot
my.plot1 <- ggplot(data.df, aes(x=TAD, y=dist1)) + geom_point() + 
  geom_line(aes(x=TAD, y=dist2)) +
  facet_grid(XID ~ FID, labeller=label_both) +
  labs(x = "TAD", y = "Response")

# alternative data structure per recommendation in
# http://stackoverflow.com/questions/15418302/ggplot2-how-to-show-the-legend?rq=1
library(reshape)
df.2 <- melt(data.df, id=c("XID","FID","TAD","time"))

I tried using data frame df.2 to see if that helps per the recommendation in the stack overflow thread I provide the link for. I tried various ggplot commands, but I still can't get it to work. Can someone please help me?

Also, how can I position the legend somewhere inside the 3x3 where there is blank space?

Thank you very much!

As for the legend drawing, use your melted dataframe and eg use colour to distinguish your two distance datasets. Eg like this:

ggplot(df.2, aes(x=TAD, y=value, colour = variable)) + geom_line() + facet_grid(XID ~ FID, labeller=label_both) + labs(x = "TAD", y = "Response")

And as for the legend positioning, I would refer you to this question with a good answer:

Position legend in first plot of facet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM