Skip to content

Missing shapes in legend with scale_shape_manual

2 messages · Howard, Tim G (DEC), Kevin Zembower

#
I believe the missing shapes are because you had set alpha=0 for the last geom point. 

I expect there are better ways, but one way to handle it would be to avoid the filtering, adding columns with med and exercise status, like the following:

# setup with data provided
Date <- c('2023-10-17', '2023-10-16', '2023-10-15', '2023-10-14',
         '2023-10-13', '2023-10-12', '2023-10-11')
Time <- c('08:50', '06:58', '09:17', '09:04', '08:44', '08:55', '07:55') 
bg <- c(128, 144, 137, 115, 136, 122, 150)
missed_meds <- c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE)
no_exercise <- c(FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE)

b2 <- data.frame(Date, Time, bg, missed_meds, no_exercise)

b2$Date <- as.Date(b2$Date)
# add "status" columns, could also be defined as factor. 
b2$medStat <- c("missed_meds",NA, NA, NA, NA, NA, "missed_meds")
b2$exercise <- c(NA, NA, "missed_exercise",NA,"missed_exercise", "missed_exercise", "missed_exercise")

Then your ggplot call would be like this:

ggplot(data = b2, aes(x = Date, y = bg)) +
  geom_line() +
  geom_point(aes(shape = medStat), size = 3)+
  geom_point(aes(shape = exercise),size = 3)+
  scale_y_continuous(name = "Blood glucose (mg/dL)",
                     breaks = seq(100, 230, by = 20)
  ) +
  geom_hline(yintercept = 130) +
  scale_shape_manual(name = "Conditions",
                     labels = c("Missed meds",
                                "Missed exercise"),
                     values = c(20, 4)
  )


Note that this method then gets very close without the scale_shape_manual, too. 

Hope that helps. 
Tim
#
Tim, thanks, it helps very much. It works like a charm.

Wow, there's so much I don't understand about ggplot2 functions,
especially the aes() function. I just discovered the ggplot2-book.org
site, and I hope to read it slowly and carefully over the next couple
of weeks.

Thanks again, Tim, for all your help.

-Kevin
On Tue, 2023-10-31 at 12:35 +0000, Howard, Tim G (DEC) wrote: