-1

Why does the following function draw a base R plot but not the GGplot equivalent?

(Base R call commented out)

library(ggplot2)
library(dplyr)

test <- function() {


  data <- data.frame("x"=1:10, "y"=1:20)

  mean <- mean(data$x)

  # Gplot, doesn't work
  data %>%
    ggplot( aes(x=x, y=y)) +
    geom_line() +
    geom_point()

  # base R plot, does work
  #plot(data$x,  data$y)


  return(mean)

}

test()
syntheso
  • 437
  • 3
  • 17

2 Answers2

4

Because you do not explicitly return it, this works:

library(ggplot2)
library(dplyr)

test <- function() {


  data <- data.frame("x"=1:10, "y"=1:20)

  mean <- mean(data$x)

  # Gplot, doesn't work
  plot_gg <- data %>%
    ggplot( aes(x=x, y=y)) +
    geom_line() +
    geom_point()

  # base R plot, does work
  #plot(data$x,  data$y)


  return(list(mean, plot_gg))

}

test()

If you want the plot to be shown without explicitly returning it, surround the plot with a print function like this (the reason you have to do this is because ggplot doesn't print when called inside a function, as mentioned here):

test <- function() {


  data <- data.frame("x"=1:10, "y"=1:20)

  mean <- mean(data$x)

  # Gplot, doesn't work
  print(data %>%
    ggplot( aes(x=x, y=y)) +
    geom_line() +
    geom_point())

  # base R plot, does work
  #plot(data$x,  data$y)


  return(mean)

}

test()
Ahorn
  • 3,686
  • 1
  • 10
  • 17
1

Unlike base plot ggplot doesn't print by default. You need to print it in the function if it isn't the last line of the function.

library(ggplot2)

test <- function() {

  data <- data.frame(x =1:10, y =1:20)
  mean <- mean(data$x)
  print(data %>%
          ggplot( aes(x=x, y=y)) +
          geom_line() +
          geom_point())

   return(mean)
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213