简体   繁体   English

使用facet_grid向ggplot添加图例

[英]Adding a legend to ggplot with facet_grid

I am creating a 3x3 faceted graph using the code shown below. 我正在使用下面显示的代码创建一个3x3的多面图。 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. 我尝试使用数据帧df.2来查看是否对我提供链接的堆栈溢出线程中的建议有所帮助。 I tried various ggplot commands, but I still can't get it to work. 我尝试了各种ggplot命令,但仍然无法正常工作。 Can someone please help me? 有人可以帮帮我吗?

Also, how can I position the legend somewhere inside the 3x3 where there is blank space? 另外,如何将图例放置在3x3内有空白的地方?

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 构面的第一个图中的位置图例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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