【问题标题】:Plotting data from function从函数中绘制数据
【发布时间】:2020-02-17 03:56:21
【问题描述】:

我想从函数中绘制数据。例如:

制作数据并加载库:

# Load ggplot2
library(ggplot2)

# Create Data
data <- data.frame(
  group=LETTERS[1:5],
  value=c(13,7,9,21,2)
)

此绘图按预期工作:

# Basic piechart
ggplot(data, aes(x="", y=value, fill=group)) +
  geom_bar(stat="identity", width=1, color="white") +
  coord_polar("y", start=0) +

  theme_void() # remove background, grid, numeric labels

但如果我尝试从函数内部进行绘图:

a <- function(data)
{
  # Basic piechart
  ggplot(data, aes(x="", y=value, fill=group)) +
    geom_bar(stat="identity", width=1, color="white") +
    coord_polar("y", start=0) +

    theme_void() # remove background, grid, numeric labels
  return()
}


a(data)

它只是给我输出:

NULL

不画任何情节。

问题:在我的示例中如何从函数中绘制绘图?

示例取自:https://www.r-graph-gallery.com/piechart-ggplot2.html

【问题讨论】:

    标签: r function ggplot2 functional-programming


    【解决方案1】:

    使您的功能发挥作用的选项。

    选项 - 我

    去掉return ()这行,基本是在函数结束的时候返回NULL(你的plot是函数a的局部,而且plot在函数外是无法访问的,没有传参返回) .

    a <- function(data)
    {
      # Basic piechart
      ggplot(data, aes(x="", y=value, fill=group)) +
        geom_bar(stat="identity", width=1, color="white") +
        coord_polar("y", start=0) +
        theme_void() # remove background, grid, numeric labels
    }
    

    选项-II

    将局部变量上的绘图保存到函数中,并在完成时返回。

    a <- function(data)
    {
      # Basic piechart
      p <- ggplot(data, aes(x="", y=value, fill=group)) +
        geom_bar(stat="identity", width=1, color="white") +
        coord_polar("y", start=0) +
       theme_void() # remove background, grid, numeric labels
      return(p)
    }
    

    选项 - III

    使用environment = environment(),它在调用ggplot 时将环境变量显式设置为当前环境。你可以在Use of ggplot() within another function in R阅读更多信息。

    a <- function(data)
    {
      # Basic piechart
      p <- ggplot(data, aes(x="", y=value, fill=group), environment = environment()) 
        p + geom_bar(stat="identity", width=1, color="white") +
        coord_polar("y", start=0) +  
        
        theme_void() # remove background, grid, numeric labels
      
    }
    
    

    现在您可以使用a(data) 来打印输出。

    输出

    【讨论】:

    • 那么,environment = environment() 是否使ggplot 的所有全局变量可见?如果不是,它的作用是什么?如果是,为什么有必要?是否有任何其他方法不会将所有全局变量暴露给在函数内部调用的ggplot
    • 查看Use of ggplot() within another function in R 以获得替代方案和讨论。
    • 我是否正确理解 environment = environment() 使 ggplot 所有全局变量可见?
    • 谢谢。非常有用的更新。
    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多