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.
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() .
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.
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() .
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”).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With