0

I am creating a scatterplot to show the relationship between Very Active Minutes of exercise and Calories burned. In my scatterplot I want the points to be green after 30 minutes of activity. Below is the code I am currently using, but I do not know how to add a criteria to change color.

ggplot(data=daily_activity) +
  geom_point(mapping=aes(x=VeryActiveMinutes, y=Calories), color="darkred") +
  geom_smooth(mapping=aes(x=VeryActiveMinutes, y=Calories)) +
  labs(title="The Relationship Between Very Active Minutes and Calories Burned", 
       caption = "Data collected from the FitBit Fitness Tracker Data on Kaggle")
camille
  • 16,432
  • 18
  • 38
  • 60
  • 1
    Welcome to SO! To help us to help you would you mind sharing [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. To share your data, you could type `dput(NAME_OF_DATASET)` into the console and copy & paste the output starting with `structure(....` into your post. If your dataset has a lot of observations you could do e.g. `dput(head(NAME_OF_DATASET, 10))` for the first ten rows of data. – stefan Mar 03 '22 at 17:45
  • 2
    Also. Maybe [Plot with conditional colors based on values in R](https://stackoverflow.com/questions/11838278/plot-with-conditional-colors-based-on-values-in-r) helps to answer your question. – stefan Mar 03 '22 at 17:47
  • 1
    This is not at all about the question itself, but you'll have an easier time debugging your own code (and having your code be legible to others) if you use some spaces, such as between arguments, and break things into multiple lines where it's syntactically allowable – camille Mar 03 '22 at 17:54
  • Please provide enough code so others can better understand or reproduce the problem. – Community Mar 04 '22 at 13:00

1 Answers1

1

As suggested by @stefan color based on the ifelse statement, and then apply those colours to the graph using scale color identity:

Sample code:

daily_activity %>% 
    mutate(Color = ifelse(VeryActiveMinutes > 30, "green", "red"))%>% 
    ggplot(aes(x=VeryActiveMinutes, y=Calories, color=Color)) +
      geom_point() +
      geom_smooth(mapping=aes(x=VeryActiveMinutes, y=Calories)) +
      labs(title="The Relationship Between Very Active Minutes and Calories Burned", 
           caption = "Data collected from the FitBit Fitness Tracker Data on Kaggle")

Output:

enter image description here

Rfanatic
  • 2,224
  • 1
  • 5
  • 21