如何使用d_plyr时包括在ggplot传奇各级(How to include all levels

2019-10-19 01:06发布

目标:其中包含的一个因素两个层面的传说,即使双方水平不图上代表

最小的可重复的例子:

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)

问题

不过 ,如果我使用一个plyr功能,每个小区打印到PDF的一个单独的页面,为L-型的传说只包含出现在该数据帧的子集的单因子水平d_ply传递给ggplot -也就是说,它只是说“富”。 我想可以说既有“foo”和“酒吧”,即使因素L-型的水平“条”不图中的发生:

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这种效果)

Answer 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")


文章来源: How to include all levels in a ggplot legend when using d_plyr
标签: r ggplot2 plyr