如何在facet_grid中指定列或如何在facet_wrap中更改标签

Slo*_*ner 40 r ggplot2

我有大量的数据系列,我想用小倍数绘制.ggplot2的组合和facet_wrap我想要的,通常产生一个漂亮的小块6 x 6面.这是一个更简单的版本:

facet_wrap

问题是我对小面条上的标签没有足够的控制.数据框中列的名称很短,我希望保持这种方式,但我希望facet中的标签更具描述性.我可以使用,facet_grid以便我可以利用该labeller功能,但似乎没有直接的方式来指定列数和一长串的方面只是不适用于此特定任务.我错过了一些明显的东西吗

facet_grid

问:如何在不更改列名的情况下使用facet_wrap时更改构面标签?或者,如何在使用facet_grid时指定列数和行数?

下面是简化示例的代码.在现实生活中,我正在处理多个组,每个组包含数十个数据系列,每个系列都经常更改,因此任何解决方案都必须自动化,而不是依赖于手动分配值.

require(ggplot2)
require(reshape)

# Random data with short column names
set.seed(123)
myrows <- 30
mydf <- data.frame(date = seq(as.Date('2012-01-01'), by = "day", length.out = myrows),
                   aa = runif(myrows, min=1, max=2),
                   bb = runif(myrows, min=1, max=2),
                   cc = runif(myrows, min=1, max=2),
                   dd = runif(myrows, min=1, max=2),
                   ee = runif(myrows, min=1, max=2),
                   ff = runif(myrows, min=1, max=2))

# Plot using facet wrap - we want to specify the columns
# and the rows and this works just fine, we have a little block
# of 2 columns and 3 rows

mydf <- melt(mydf, id = c('date'))

p1 <- ggplot(mydf, aes(y = value, x = date, group = variable)) +
    geom_line() +
    facet_wrap( ~ variable, ncol = 2)
print (p1)

# Problem: we want more descriptive labels without changing column names.
# We can change the labels, but doing so requires us to
# switch from facet_wrap to facet_grid
# However, in facet_grid we can't specify the columns and rows...

mf_labeller <- function(var, value){ # lifted bodily from the R Cookbook
    value <- as.character(value)
    if (var=="variable") {
        value[value=="aa"]   <- "A long label"
        value[value=="bb"]   <- "B Partners"
        value[value=="cc"]   <- "CC Inc."
        value[value=="dd"]   <- "DD Company"
        value[value=="ee"]   <- "Eeeeeek!"
        value[value=="ff"]   <- "Final"
    }
    return(value)
}

p2 <- ggplot(mydf, aes(y = value, x = date, group = variable)) +
    geom_line() +
    facet_grid( ~ variable, labeller = mf_labeller)
print (p2)
Run Code Online (Sandbox Code Playgroud)

jor*_*ran 20

我不太明白.您已经编写了一个功能,可以将短标签转换为长的描述性标签.简单地添加新列并facet_wrap在该列上使用会出现什么问题?

mydf <- melt(mydf, id = c('date'))
mydf$variableLab <- mf_labeller('variable',mydf$variable)

p1 <- ggplot(mydf, aes(y = value, x = date, group = variable)) +
    geom_line() +
    facet_wrap( ~ variableLab, ncol = 2)
print (p1)
Run Code Online (Sandbox Code Playgroud)

  • 添加新专栏没有错 - 我的大脑在最后一步之前放弃了!我应该知道这样做."如果有疑问,将列添加到数据框"实际上是ggplot的默认帮助声明.谢谢. (10认同)

Pau*_*tra 8

要更改标签名称,只需更改您使用的因子的因子级别facet_wrap.这些将用于facet_wrap条带上.您可以使用与使用该labeller功能类似的设置facet_grid.做一些像:

new_labels = sapply(levels(df$factor_variable), custom_labeller_function)
df$factor_variable = factor(df$factor_variable, levels = new_labels)
Run Code Online (Sandbox Code Playgroud)

现在你可以使用factor_variablefacet_wrap.