r - 将表达式(plotmath)放入图例键标签中

标签 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")

最佳答案

如果我使用两者 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

关于r - 将表达式(plotmath)放入图例键标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368191/

相关文章:

r - 函数内的计数(dplyr)问题

r - Shiny 的 : Input to asJSON(keep_vec_names=TRUE) is a named vector 中的警告 jsonlite

r - 使用形状时缺少 geom_point 的绘图符号

r - 沿离散尺度调整几何位置

r - 没有轴或网格的 ggplot2 主题

r - 数据表与 dplyr : can one do something well the other can't or does poorly?

使用 sapply 复制嵌套循环

r - 使用 ggsave() 保存时覆盖在 ggplot2 条形图上的线条

r - 如何在ggplot2图例中包含黄土线?

R 如果满足条件或者是特定行号,则删除行