【问题标题】:Create user function for ggplot为 ggplot 创建用户函数
【发布时间】:2019-06-28 09:21:45
【问题描述】:

我正在尝试创建一个函数来编辑 ggplot 的外观。

这是我想用函数创建的示例(显然我要创建的函数更复杂,但这是为了演示)。

library(ggplot2)
library(dplyr)
group_by(iris, Species) %>%
  summarise(m = mean(Sepal.Width)) %>%
  ggplot(aes(x = Species, y = m)) +
  geom_col() + 
  xlab("") + ylab("")

这是我正在尝试制作的功能:

name_axis <- function(){
  xlab(label = "") + 
  ylab(label = "")   
}

group_by(iris, Species) %>%
  summarise(m = mean(Sepal.Width)) %>%
  ggplot(aes(x = Species, y = m)) +
  geom_col() + 
  name_axis()

我知道我可以这样做,首先将绘图保存到一个对象,然后将绘图传递给新函数。但我想跳过这一步,改用“+”。

【问题讨论】:

  • 那么,您希望坐标区根本不显示任何标签吗?
  • 在本例中是。我正在尝试为 ggplot 创建一系列“外观功能”以标准化外观。因此,一个函数将具有轴名称的参数,以及 y 轴是否应显示百分比等。

标签: r ggplot2


【解决方案1】:

你可以这样做

  1. list()
    name_axis <- list(
      xlab(label = "Nothing"),  
      ylab(label = ""))

    group_by(iris, Species) %>%
      summarise(m = mean(Sepal.Width)) %>%
      ggplot(aes(x = Species, y = m)) +
      geom_col() + 
      name_axis
  1. 在函数内部传递一个列表:
  name_axis <- function(){
      list(xlab(label = ""), 
        ylab(label = "hello"))   
    }

   group_by(iris, Species) %>%
      summarise(m = mean(Sepal.Width)) %>%
      ggplot(aes(x = Species, y = m)) +
      geom_col() + 
      name_axis()```

【讨论】:

  • 哇,好吧,我不知道你可以使用列表来完成这项任务。非常感谢您的提示。这解决了我的问题。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-12-27
  • 2012-03-15
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
相关资源
最近更新 更多