0

I would like to create a line graph where I have a single colored line but where points have a different color depending on a variable in the dataset (demonstrating LOCF model as part of project). I have attached my code & its corresponding output below:

suppressPackageStartupMessages(library(mice))
suppressPackageStartupMessages(library(tidyverse))
airquality_indicator <- airquality %>% 
  mutate(imputation_indicator = if_else(is.na(Ozone), "imputed", "observed"))

airquality2 <- tidyr::fill(airquality_indicator, Ozone)
head(airquality2, 30) %>% ggplot(aes(x = Day,y= Ozone, color = imputation_indicator)) + 
  geom_line() + 
  geom_point() + 
  labs(y = "ozone  (ppb)",
       x = "Day Number")

code output Meanwhile, here is the desired output: desired output

Thank you!

Quinten
  • 35,235
  • 5
  • 20
  • 53
Ator
  • 5
  • 1
  • 1
    If you only want to color the points do the mapping only in that layer. Use: `head(airquality2, 30) %>% ggplot(aes(x = Day,y= Ozone)) + geom_line() + geom_point(aes(color=imputation_indicator)) + labs(y = "ozone (ppb)",x = "Day Number")` – MrFlick Jun 27 '22 at 14:08

1 Answers1

0

Move the colour to the geom_point aesthetic. Add , show.legend = FALSE if you don't want the legend.

suppressPackageStartupMessages(library(mice))
#> Error in library(mice): there is no package called 'mice'
suppressPackageStartupMessages(library(tidyverse))

airquality_indicator <- airquality %>%
  mutate(imputation_indicator = if_else(is.na(Ozone), "imputed", "observed"))

airquality2 <- tidyr::fill(airquality_indicator, Ozone)

head(airquality2, 30) %>% 
  ggplot(aes(Day, Ozone)) +
  geom_line() +
  geom_point(aes(color = imputation_indicator)) +
  labs(
    y = "ozone  (ppb)",
    x = "Day Number"
  )

Created on 2022-06-27 by the reprex package (v2.0.1)

Carl
  • 4,232
  • 2
  • 12
  • 24