Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tidyverse line plot single line with multiple dot colors

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading