Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass aes parameters of ggplot to function

I am using gapminder and trying to write a simple function showing graphs of lifeExp against gdpPercap. However, when I put the arguments in the function, the arguments are not recognised.

I have tried several answers, with no results yet.

plotting <- function (input, xx, yy){
  library (ggplot2)
  library (gapminder)
  ggplot (input, aes (xx, yy, size = pop, color = country)) + geom_point(show.legend = FALSE) 
}  

When I run plotting (gampinder, lifeExp, gdpPercap) to be used as input, xx and yy, the result is

"Error in FUN(X[[i]], ...) : object 'gdpPercap' not found"`

This is where I am stuck and gdpPercap is there but not found by the code! Could you please help.

like image 392
Rassoul Avatar asked Nov 10 '19 06:11

Rassoul


People also ask

What does AES () do in ggplot?

aes() is a quoting function. This means that its inputs are quoted to be evaluated in the context of the data. This makes it easy to work with variables from the data frame because you can name those directly. The flip side is that you have to use quasiquotation to program with aes() .

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot. ggplot2 comes with many geom functions that each add a different type of layer to a plot.

What does AES do in R?

In R, the aes() function is often used within other graphing elements to specify the desired aesthetics. The aes() function can be used in a global manner (applying to all of the graph's elements) by nesting within ggplot() .

Which three elements are required to run the ggplot () function?

3.1 Elements of a ggplot Producing a plot with ggplot2 , we must give three things: A data frame containing our data. How the columns of the data frame can be translated into positions, colors, sizes, and shapes of graphical elements (“aesthetics”). The actual graphical elements to display (“geometric objects”).


1 Answers

You need to use tidy evaluation inside aes(). Either .data[[ ]] or {{ }} (curly curly) would work. See also this answer and Tidy evaluation section in Hadley Wickham's Advanced R book.

library(gapminder)
library(rlang)
library(ggplot2)

plotting <- function(input, xx, yy) {
  ggplot(input, aes(.data[[xx]], .data[[yy]], size = pop, color = country)) +
    geom_point(show.legend = FALSE)
}

plotting(gapminder, "lifeExp", "gdpPercap")

plotting2 <- function(input, xx, yy) {
  ggplot(input, aes({{xx}}, {{yy}}, size = pop, color = country)) +
    geom_point(show.legend = FALSE)
}

plotting2(gapminder, lifeExp, gdpPercap)

Created on 2019-11-09 by the reprex package (v0.3.0)

like image 81
Tung Avatar answered Oct 23 '22 06:10

Tung