Home > Software design >  Why can't ggplot separate plots from this example from the r4ds book?
Why can't ggplot separate plots from this example from the r4ds book?

Time:11-28

I am Learning R with the book R for Data Science 2017 - H.Wickham G.Grolemund I have a problem in the page 16 42/520. This is the code:

ggplot(data = mpg)  
geom_smooth(mapping = aes(x = displ, y = hwy))

ggplot(data = mpg)  
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))

ggplot(data = mpg)  
geom_smooth(
mapping = aes(x = displ, y = hwy, color = drv),
show.legend = FALSE
)

with this plot:

enter image description here

This is the text reference:

Many geoms, like geom_smooth(), use a single geometric object to display multiple rows of data. For these geoms, you can set the group aesthetic to a categorical variable to draw multiple objects. ggplot2 will draw a separate object for each unique value of the grouping variable. In practice, ggplot2 will automatically group the data for these geoms whenever you map an aesthetic to a discrete variable (as in the linetype example). It is convenient to rely on this feature because the group aesthetic by itself does not add a legend or distinguishing features to the geoms:

I try to reproduce but my plot is this:

enter image description here

I don't know if this is an version error or this way of plotting was deprecated.

CodePudding user response:

Do you want this?

ggplot(data = mpg)  
  geom_smooth(
    mapping = aes(x = displ, y = hwy, color = drv),
    show.legend = FALSE
  )  
  facet_wrap(~drv, scales = "free_x")

enter image description here

  • Related