使用dplyr时如何在ggplot图例中包含所有级别

时间:2013-11-23 01:27:22

标签: r ggplot2 plyr

目标:包含两个级别因素的图例,即使图中未显示两个级别

最小可重复的例子:

library(ggplot2)
library(plyr)

mre <- data.frame(plotfactor = factor(rep(c("response1", "response2"), c(2, 
    2))), linefactor = factor(rep(c("line1", "line2"), 2)), x1 = runif(n = 4), 
    x2 = runif(n = 4), y1 = runif(n = 4), y2 = runif(n = 4), ltype = c("foo", 
        "foo", "foo", "bar"))

## this looks great!
ggplot(mre, aes(x = x1, xend = x2, y = y1, yend = y2, colour = linefactor, 
linetype =  ltype)) + geom_segment() + facet_wrap(~plotfactor)

pretty example

问题

但是,如果我使用plyr函数将每个绘图打印到一个单独的页面 pdf,ltype的图例仅包含出现在d_ply传递给ggplot的数据帧子集中的单因子级别 - 即,它只显示“foo”。我希望它同时说“foo”和“bar”,即使因子ltype的级别“bar”没有出现在图表中:

pdf("test.pdf")
d_ply(mre, .(plotfactor), function(DF)
    g <- ggplot(DF, aes(x = x1, xend = x2, y = y1, yend = y2, colour = linefactor,
    linetype = ltype)) + geom_segment()
    print(g)
    })
dev.off()

(原谅我:我不知道如何在png中产生这种效果)

1 个答案:

答案 0 :(得分:1)

您需要使用scale_linetype_discrete来确保两者都在图例上。

mre$ltype <- factor(mre$ltype)


plot1 <- ggplot(subset(mre, plotfactor == "response1"), 
    aes(x = x1, xend = x2, y = y1, yend = y2, colour = linefactor, 
    linetype =  ltype)) + 
    geom_segment()  +
    scale_linetype_discrete(drop = FALSE)
    ggsave(plot1, file = "plot1.pdf")

plot2 <- ggplot(subset(mre, plotfactor == "response2"), 
    aes(x = x1, xend = x2, y = y1, yend = y2, colour = linefactor, 
    linetype =  ltype)) + 
    geom_segment()  +
    scale_linetype_discrete(drop = FALSE)
    ggsave(plot2, file = "plot2.pdf")