-1

I have created a plot of smooth lined curves of some data along with the corresponding data points with the following code in rstudio:

#begin code
library(ggplot2)
ggplot(mydata, aes(x,y)) + geom_point() + geom_smooth()
p <- ggplot() +

# blue plot
geom_point(data=mydata, aes(x,y)) +
geom_smooth(data=mydata, aes(x,y),fill="blue",
colour ="darkblue", size=1) +

# red plot
geom_point(data=mydata, aes(x,y2)) +
geom_smooth(data=mydata, aes(x,y2), fill="darkred",
colour="red", size=1)

p + xlab('Density') + ylab("Potential Energy (MeV)") 

#endcode

Where data is fed in as x,y,y2 in three columns.

I can get the graphs to work just find, but I cannot figure out how to add a legend. The native legend() function does not work and any attempt to use theme() or scale_colour_manual() just returns the graphs unaltered. How can I add a legend or graphic to differentiate the red and blue curves?

Cyrus Mohammadian
  • 4,982
  • 6
  • 33
  • 62
  • please provide a reproducible example – Cyrus Mohammadian Sep 08 '16 at 18:19
  • 3
    You are not using ggplot in the way that it is intended. Scales should be added automatically if you shape your data correctly. You can then use scale_color_blah to change the scales. Try something along these lines. You need to create a new data.frame that stacks the two columns of y's on top of each other, then create an indicator (`var` in this case) for y and y2. `mydata = data.frame(x = c(mydata$x, mydata$x), y = c(mydata$y, mydata$2), var = c(rep(0, LENGTH OF Y), rep(1, LENGTH of Y2))); ggplot(data = iris, aes(x = x, y = y, color = var)) + geom_point() + geom_smooth()` – Vlo Sep 08 '16 at 18:21

1 Answers1

1

This is the data I used as an example.

   mydata=data.frame(x=seq(1,10),
                  y1=floor(runif(min = 1,max=10,10)),
                  y2=floor(runif(min = 1,max=10,10)))

To have it work with ggplot2 I used the function melt from the reshape2 library.

 mydata=melt(mydata,measure.vars = c("y1","y2")) 

I then used the following code, lmk if that fits your need:

ggplot(mydata,aes(x,value))+
  geom_point(aes(fill=as.factor(variable)))+
  geom_smooth(aes(fill=as.factor(variable)))+
  scale_fill_manual(values=c("red","blue"),guide=guide_legend(title="Variable"))
Haboryme
  • 4,611
  • 2
  • 18
  • 21