Home > Back-end >  Error with check_aesthetics when trying to use geom_rug in {ggplot}
Error with check_aesthetics when trying to use geom_rug in {ggplot}

Time:10-25

I am trying to generate a plot using the data frame "swiss" built into R. I'm trying to add rug to a plot of Fertility ~ Education, but only plotting the rug for provinces where more than 50% of males are involved in Agriculture as an occupation. Here's the code I have so far:

ggplot(data = swiss)   
  geom_point(mapping = aes(x = Education, y = Fertility))   
  geom_smooth(method = "lm", aes(x = Education, y = Fertility), se = FALSE)   
  geom_smooth(method = "loess", aes(x = Education, y = Fertility, 
                                    col = "red"), 
              linetype = "dotted", 
              lwd = 2,
              se = FALSE)   
  geom_rug(mapping = aes(x = Education[Agriculture >= 50], y = Fertility[Agriculture >= 50]), 
           color = "blue")

When I run this code I receive the error: error in check_aesthetics(): Aesthetics must be length 1 or the same as data (47), x and y.

I know both subsets are equal to 26, and I've tried subsetting the data beforehand (both x and y) and then running the code, but that gives me an error in fortify(). The fortify() error occurs even after I call the subsetted data as a data frame.

I'm at a loss for what to try next, so any suggestions are helpful. Here's what the plot is supposed to look like for reference.

Expected output

1Yi2T8.png

CodePudding user response:

The issue is that you subset the vectors. Instead subset the data used for geom_rug:

library(ggplot2)

ggplot(data = swiss)  
  geom_point(mapping = aes(x = Education, y = Fertility))  
  geom_smooth(method = "lm", aes(x = Education, y = Fertility), se = FALSE)  
  geom_smooth(
    method = "loess", aes(
      x = Education, y = Fertility,
      col = "red"
    ),
    linetype = "dotted",
    lwd = 2,
    se = FALSE
  )  
  geom_rug(
    data = subset(swiss, Agriculture >= 50), mapping = aes(x = Education, y = Fertility),
    color = "blue"
  )
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

And to show the rug only at the bottom as in the image you posted then you have to set sides="b":

library(ggplot2)

ggplot(data = swiss)  
  geom_point(mapping = aes(x = Education, y = Fertility))  
  geom_smooth(method = "lm", aes(x = Education, y = Fertility), se = FALSE)  
  geom_smooth(
    method = "loess", aes(
      x = Education, y = Fertility,
      col = "red"
    ),
    linetype = "dotted",
    lwd = 2,
    se = FALSE
  )  
  geom_rug(
    data = subset(swiss, Agriculture >= 50), mapping = aes(x = Education, y = Fertility),
    color = "blue",
    sides = "b"
  )
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

  • Related