0

I am having trouble adding a legend to my plot. I want the plot to have points and lines, that is why I am using both geom_line() and geom(points). Here is my code with some made up numbers. When I move "color" into "aes", somehow I get an error and I cannot plot it.

meanted=rnorm(13)
meantotal=rnorm(13)
meantedneg=rnorm(13)
meantedpos=rnorm(13)
totaldf=data.frame(x=c(0:12),meanted,meantotal,meantedneg,meantedpos)


pic=ggplot()+
  geom_point(data=totaldf,aes(x=-x,y=meantedneg), color = "red")+
  geom_point(data=totaldf,aes(x=-x,y=meantedpos), color = "blue")+
  geom_point(data=totaldf,aes(x=-x,y=meanted), color = "green")+
  geom_point(data=totaldf,aes(x=-x,y=meantotal),color = "black")+
  geom_line(data=totaldf,aes(x=-x,y=meantedneg), color = "red")+
  geom_line(data=totaldf,aes(x=-x,y=meantedpos), color = "blue")+
  geom_line(data=totaldf,aes(x=-x,y=meanted), color = "green")+
  geom_line(data=totaldf,aes(x=-x,y=meantotal),color = "black")

print(pic)
  • 2
    Reshape your data. Here is a post about the topic: [Plotting two variables as lines using ggplot2 on the same graph](https://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-on-the-same-graph) – markus Jan 11 '21 at 14:35
  • Not sure who downvoted this question. Please don't be discouraged by this - it was an OK first question, and you gave us some sample data. Nothing wrong with it. – tjebo Jan 11 '21 at 16:36

1 Answers1

4

As markus said, ggplot2 will do this for you if you pivot/reshape the data so that each of your desired legend objects are defined in a single column.

Pivoting/reshaping means going from a "wide" format to a "long" format. I'll use tidyr::pivot_longer, though it can be done with reshape (not my preference) or data.table::melt:

tidyr::pivot_longer(totaldf, -x)
# # A tibble: 52 x 3
#        x name         value
#    <int> <chr>        <dbl>
#  1     0 meanted     1.37  
#  2     0 meantotal  -0.279 
#  3     0 meantedneg -0.257 
#  4     0 meantedpos  0.0361
#  5     1 meanted    -0.565 
#  6     1 meantotal  -0.133 
#  7     1 meantedneg -1.76  
#  8     1 meantedpos  0.206 
#  9     2 meanted     0.363 
# 10     2 meantotal   0.636 
# # ... with 42 more rows

From here,

library(ggplot2)
ggplot(tidyr::pivot_longer(totaldf, -x), aes(x, value, color = name, group = name)) +
  geom_path() +
  geom_point() +
  scale_color_manual(values = c(meantedneg="red", meantedpos="blue", meanted="green", meantotal="black"))

ggplot2 with legend, preserving colors

(FYI, I pre-seeded the randomness with set.seed(42) to get this random data.)

r2evans
  • 141,215
  • 6
  • 77
  • 149