Plotting data from function

Viewed 83

I want to plot data from function. For example:

Make data and load libraries:

# Load ggplot2
library(ggplot2)

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

This plotting works as intended:

# 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

But if I try to plot from inside of function:

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)

it just gives me output:

NULL

without drawing any plot.

Question: How to make draw plot from function in my example?

example taken from: https://www.r-graph-gallery.com/piechart-ggplot2.html

1 Answers

The options to make your function work.

Option - I

Remove the line return (), which basically returns NULL when the function finishes (your plot is local to the function a, and the plot is not accessible outside the function, and no parameter is passed to return).

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
}

Option-II

Save your plot on a local variable to the function and return it up on completion.

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)
}

Option - III

Use environment = environment() which sets the environment variable explicitly to the current environment when calling ggplot. You can read more about at 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
  
}

Now you can use a(data) to print the output.

Output

ego_function

Related