代码之家  ›  专栏  ›  技术社区  ›  mathematical.coffee

ggplot中轴/变量标签的键值映射

  •  6
  • mathematical.coffee  · 技术社区  · 7 年前

    我经常使用具有“r-friendly”/“programmer-friendly”列名称的数据帧,通常没有空格和/或缩写(在进行分析时懒得输入全名)。例如:

    ir <- data.frame(
       sp=iris$Species,
       sep.len=iris$Sepal.Length,
       sep.wid=iris$Sepal.Width,
       pet.len=iris$Petal.Length,
       pet.wid=iris$Petal.Width
    )
    

    当我用g g plot绘制这些图时,我经常想用“用户友好”的列名替换标签,例如

    p <- ggplot(ir, aes(x=sep.len, y=sep.wid, col=sp)) + geom_point() +
      xlab("sepal length") + ylab("sepal width") + 
      scale_color_discrete("species")
    

    问题: 有什么方法可以指定要传递到ggplot的标签映射吗?

    lazy.labels <- c(
      sp     ='species',
      sep.len='sepal length',
      sep.wid='sepal width',
      pet.len='petal length',
      pet.wid='petal width'
    )
    

    做一些类似的事情

    p + labs(lazy.labels)
    

    甚至

    p + xlab(lazy.labels[..x..]) + ylab(lazy.labels[..y..])
    

    哪里 ..x.. , ..y.. 某个automagic ggplot变量是否保存当前x/y变量的名称?(然后我可以将这些注释放入一个方便的函数中,而不必为每个图形更改它们)

    当我在报告中绘制许多图时,这尤其有用。我可以改名 ir 有了“用户友好”的专栏,但是接下来我要做很多

    ggplot(ir, aes(x=`sepal length`, y=`sepal width`, ...
    

    这有点麻烦,因为所有的空间。

    2 回复  |  直到 7 年前
        1
  •  4
  •   Axeman    7 年前

    library(ggplot2)
    
    ir <- data.frame(
      sp = iris$Species,
      sep.len = iris$Sepal.Length,
      sep.wid = iris$Sepal.Width,
      pet.len = iris$Petal.Length,
      pet.wid = iris$Petal.Width
    )
    
    p <- ggplot(ir, aes(x=sep.len, y=sep.wid, col=sp)) +
         geom_point() +
         scale_color_discrete("species")
    
    
    ## for lazy labels
    
    lazy.labels <- c(
      sp     ='species',
      sep.len='sepal length',
      sep.wid='sepal width',
      pet.len='petal length',
      pet.wid='petal width'
    )
    
    p$labels <-lapply(p$labels,function(x){as.character(lazy.labels[x])})
    

    plot_with_labels <- function(p, l) {
      p$labels <- lapply(p$labels, function(x) { as.character(l[x]) } )
      return(p)
    }
    
    plot_with_labels(p, lazy.labels)
    
        2
  •  1
  •   cderv    7 年前

    labs(lazy.labels)

    ir <- data.frame(
      sp = iris$Species,
      sep.len = iris$Sepal.Length,
      sep.wid = iris$Sepal.Width,
      pet.len = iris$Petal.Length,
      pet.wid = iris$Petal.Width
    )
    library(ggplot2)
    # mapping aesthetics names to labels
    lazy.labels <- list(
      col = 'species',
      x = 'sepal length',
      y ='sepal width'
    )
    p <- ggplot(ir, aes(x = sep.len, y = sep.wid, col = sp)) + 
      geom_point() +
      labs(lazy.labels)
    

    reprex package