Using ggplot to plot transformed variables?

  • Using ggplot to plot transformed variables?

     David updated 1 month, 1 week ago 2 Members · 4 Posts
  • jordan.trachtenberg

    Member
    October 21, 2020 at 11:36 am

    I have a question about plotting data transformations.

    Will ggplot only plot variables that are stored in the dataframe? For instance, I tried to create a new variable, height_in_ft:

    nhanes %>%

    mutate(height_in_ft = height/(2.54*12)) %>%

    ggplot(data = nhanes,

    mapping = aes(x = weight,

    y = height_in_ft,

    color = gender)) +

    geom_point()

    and got this error,

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

    whereas if I apply the data transformation within the ggplot function, it works with no problem:

    nhanes %>% 
    ggplot(data = nhanes,
    mapping = aes(x = weight,
    y = height/(2.54*12),
    color = gender)) +
    geom_point()

  • David

    Organizer
    October 21, 2020 at 3:11 pm

    ggplot will plot any variables you create. However, because you are telling it to use the nhanes data frame again, it will use that, and not any variables you’ve created in your pipeline. Try this (not that I removed data = nhanes):

    nhanes %>%

    mutate(height_in_ft = height/(2.54*12)) %>%

    ggplot(mapping = aes(x = weight,

    y = height_in_ft,

    color = gender)) +

    geom_point()

    • jordan.trachtenberg

      Member
      October 22, 2020 at 6:25 am

      Aha! That makes sense. So I guess there would be no reason to use data = nhanes unless you didn’t initially identify your dataframe at the beginning of the statement.

  • David

    Organizer
    October 22, 2020 at 7:19 am

    Yup, that’s exactly right.

Log in to reply.

Original Post
0 of 0 posts June 2018
Now
The R for the Rest of Us community is live! Join regular office hours, ask questions in the forum, and more!