将表达式(plotmath)放在图例键标签中

时间:2012-04-28 22:41:47

标签: r ggplot2

如何将表达式(plotmath)放入下图的图例键标签中?

我知道How to use Greek symbols in ggplot2?及其中的链接,但每当我使用scale_..._manual函数时,我都会获得第二个图例(见下文)。

require(ggplot2)
require(reshape2)
require(plyr)

## parameters
d <- c(2, 5, 10, 20, 50, 100)
tau <- c("t1", "t2", "t3")
fam <- c("f1", "f2", "f3", "f4", "f5")
meth <- c("m1", "m2", "m3", "m4")

## lengths
nd <- length(d)
ntau <- length(tau)
nfam <- length(fam)
nmeth <- length(meth)

## build result array containing the measurements
arr <- array(rep(NA, nd*ntau*nfam*nmeth), dim=c(nd, ntau, nfam, nmeth),
             dimnames=list(d=d, tau=tau, fam=fam, meth=meth))
for(i in 1:nd){
    for(j in 1:ntau){
        for(k in 1:nfam){
            for(l in 1:nmeth){
                arr[i,j,k,l] <- i+j+k+l+runif(1)
            }
        }
    }
}

## create molten data
mdf <- reshape2:::melt.array(arr, formula = . ~ d + tau + fam + meth) # create molten data frame
mdf$tau. <- factor(mdf$tau, levels=tau, labels=paste("tau==", tau, sep="")) # expression for tau
mdf$fam. <- factor(mdf$fam, levels=fam, labels=paste("alpha==", fam, sep="")) # expression for family
meth.labs <- lapply(1:nmeth, function(i) bquote(gamma==.(i))) # expression for methods

## plot
ggplot(mdf, aes(x=d, y=value, shape=meth, linetype=meth)) + geom_line() +
    geom_point() + facet_grid(fam. ~ tau., scales="free_y", labeller=label_parsed) +
    ## scale_linetype_manual(values=1:4, breaks=meth, labels=meth.labs) + # problem: adds another legend
    scale_x_continuous(trans="log10", breaks=d, labels=d) +
    scale_y_continuous(trans="log10")

1 个答案:

答案 0 :(得分:7)

如果我使用两个 scale_*_manual函数,我会得到一个带有表达式的单个图例:

ggplot(mdf, aes(x=d, y=value, shape=meth, linetype=meth)) + geom_line() +
    geom_point() + facet_grid(fam. ~ tau., scales="free_y", labeller=label_parsed) +
    ## scale_linetype_manual(values=1:4, breaks=meth, labels=meth.labs) + # problem: adds another legend
    scale_x_continuous(trans="log10", breaks=d, labels=d) +
    scale_y_continuous(trans="log10") + 
    scale_linetype_manual(breaks = c('m1','m2','m3','m4'),values = 1:4,labels = meth.labs) +
    scale_shape_manual(breaks = c('m1','m2','m3','m4'),values = 1:4,labels = meth.labs)

enter image description here