Beginning geom point layering help

I am very much a newbie at r and when I run this code I get "%>%" not found, "model" not found (this is a variable in a beginners data frame called mpg), and my object I just defined is not found. I am wondering how to get my object I created to work. Overall my objective is simply to layer a scatterplot on top of another - the second being only 2 seater cars which are all corvettes. I am basically identifying and highlighting the outliers in a scatterplot of displ and hwy milage. Displ being the type of engine/engine size in litres.
Also most of the ways ive written it works in the script/ plot viewer but wont work when I try to knit it into r markdown.

mpg %>%
seat2mpg<-filter(model == "corvette")
ggplot(mapping = aes(x = displ, y = hwy)) +
  geom_point() +
  geom_point(seat2mpg, aes(color = "red", size = 2))

If someone could type the code in to do what im trying to do I could probably figure out where I went wrong but any help is greatly appreciated!

I think you want


seat2mpg<- mpg %>% filter(model == "corvette")

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
  geom_point() +
  geom_point(data = seat2mpg, mapping = aes(color = "red", size = 2))

The first argument of ggplot() is the data, so I did not have to name it or the mapping but I thought doing that would be clearer.
The first argument of geom_point() is mapping followed by data, so those must be named or entered in the correct order.

When you knit an Rmarkdown document, the code gets executed on a clean environment other than your current working environment, so you need to include library calls and code to import the data you are using in your Rmarkdown file.

1 Like

in addition to the other advice you have received.
In general when using R, expect to load some libraries into your session.
for example %>% relies on magrittr or dplyr packages
filter() on dplyr
ggplot and geom_point on ggplot2.
dplyr,and ggplot2 are both members of a container package for convenience
Therefore library(tidyverse) would be good for you.
( assuming you have at some previous time installed it - install.packages("tidyverse") )

Thnank you to all of you!! Every one of you solved a problem I needed help with. Can't tell you how much I appreciate all the quick replies and detailed help; though you all probably already know the feeling of getting a chunk to work after a long time fidgeting.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.