0

This might sound simple or complex, but how do I create a legend like this for my plot(I just need 1 legend for the whole group)

Legend
4=Standing
3=Stepping
2=Cycling
1=Sitting

this is the code that I have so far:

graph_pre <-  mutate(graph_pre, day = lubridate::day(Date)) 

ggplot(graph_pre, aes(x = Time, y = Posture))+
  geom_point()+
  facet_wrap(~day, scales = "free_x")

And here is the output

enter image description here

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • you need to add an aesthetic to your ggplot - typically done with `aes()` aesthetics that generate legends are most commonly color, fill, linetype, alpha, size. you can also pass a constant to it – tjebo Jun 08 '22 at 13:02
  • ok how would I do that exactly? – Richard Michaud Langis Jun 08 '22 at 13:04
  • have you checked the linked thread? You need a column that contains the given variable that assigns values to your data points (i.e., contains your _standing, stepping_ etc), and then add this, for example as color, to your ggplot, e.g., `geom_point(aes(color = your_variable))` – tjebo Jun 08 '22 at 13:07
  • 1
    You mean you want a legend for your `y` axis values? Why not just use the labels themselves on the axis? ggplot doesn't really allow for arbitrary legends for things that aren't mapped via the aesthetics. – MrFlick Jun 08 '22 at 13:08
  • 1
    @MrFlick you're probably right. I have misunderstood the OPs intention for sure – tjebo Jun 08 '22 at 13:09

1 Answers1

0

It pains me to do that, but here would be a way to show y labels in a legend.

library(ggplot2)

## faking the y legend 
ggplot(iris) +
  ## create color aesthetic
  geom_point(aes(Sepal.Length, Species, color = Species)) +
  facet_grid(~Species) +
## relabelling for demonstration purpose 
  scale_y_discrete(labels = 1:3) +
  ## change your aesthetic colors
  scale_color_manual(values = rep("black", 3)) +
  ## reshape dots to numbers
  guides(color = guide_legend(override.aes = list(shape = as.character(1:3))))

However, placing the labels to the y axis is much more natural and intuitive. You will help the reader and make your graph more appealing.

## perfect labelling on the y axis. This is where your y labelling belongs
ggplot(iris) +
  geom_point(aes(Sepal.Length, Species)) +
  facet_grid(~Species)

tjebo
  • 21,977
  • 7
  • 58
  • 94