4

How can I put expressions (plotmath) into the legend key labels of the following plot?

I am aware of How to use Greek symbols in ggplot2? and the link therein, but whenever I use scale_..._manual function, I obtain a second legend (see below).

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

1 回答 1

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)

在此处输入图像描述

于 2012-04-29T00:04:18.167 回答