Ggplot2 aes_string () does not like "rownames (mtcars)" when inside a function

I need to create a graph inside the function, relying on aes_string(), and I need labels as the names of the growths.

The following graph works fine, but not inside the function .

library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
  g <- ggplot(data = cars, aes_string(x = "mpg", y = "disp", label = "rownames(cars)"))
  g <- g + geom_point()
  g <- g + geom_text()
  g
}
plotfun(cars = mtcars)

When run as a function, this is me:

Error: Aesthetics must either be length one, or the same length as the dataProblems:mpg, disp

I can’t circle my head. I know that there are many similar questions about the aes_string()inside of a function - I just could not adapt my solutions to my problem.

Ps: obviously, above MWE is pretty stupid; in my actual use case, I run a graph for loops, therefore, required aes_string().

+4
source share
2 answers

, < <20 > , aes_string

library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
  g <- ggplot(data = cars, aes_q(x = as.name("mpg"), y = as.name("disp"), label=rownames(cars)))
  g <- g + geom_point()
  g <- g + geom_text()
  g
}
plotfun(cars = mtcars)

aes_q , as.name() , .

+4

deparse aes_string:

plotfun <- function(cars) {
  g <- ggplot(data = cars, aes_string(x = "mpg", y = "disp", 
              label = deparse(rownames(cars))))
  g <- g + geom_point()
  g <- g + geom_text()
  g
}

plotfun(cars = mtcars)

enter image description here

deparse , .. (rownames(cars)), , mtcars:

> deparse(rownames(mtcars))
[1] "c(\"Mazda RX4\", \"Mazda RX4 Wag\", \"Datsun 710\", \"Hornet 4 Drive\", "         
[2] "\"Hornet Sportabout\", \"Valiant\", \"Duster 360\", \"Merc 240D\", \"Merc 230\", "
[3] "\"Merc 280\", \"Merc 280C\", \"Merc 450SE\", \"Merc 450SL\", \"Merc 450SLC\", "   
[4] "\"Cadillac Fleetwood\", \"Lincoln Continental\", \"Chrysler Imperial\", "         
[5] "\"Fiat 128\", \"Honda Civic\", \"Toyota Corolla\", \"Toyota Corona\", "           
[6] "\"Dodge Challenger\", \"AMC Javelin\", \"Camaro Z28\", \"Pontiac Firebird\", "    
[7] "\"Fiat X1-9\", \"Porsche 914-2\", \"Lotus Europa\", \"Ford Pantera L\", "         
[8] "\"Ferrari Dino\", \"Maserati Bora\", \"Volvo 142E\")"   

aes_string.

+4

Source: https://habr.com/ru/post/1598441/


All Articles