1

I am trying to color my lines in ggplot to be red and blue, but they seem to have reversed colors.

ggplot(data.frame(x)) +
  geom_line(aes(x=x, y=y, color='blue')) +
  geom_line(aes(x=x, y=y2, color='red')) +
  labs(title ="Normal Distribution Curve & Normal CDF Curve ")

To that end, how can I override the text in the legend to not say "red" and "blue" but instead be labeled "distribution 1" and "distribution 2"?

img

camille
  • 16,432
  • 18
  • 38
  • 60
Jackson Walker
  • 137
  • 1
  • 9
  • 1
    It's not that they've reversed colors, it's that you need to assign a variable to color, the way ggplot expects. Then if you have specific colors you want to use, you set a scale. Take a look through the [docs](http://ggplot2.tidyverse.org/), which have a lot of examples and link to tutorials – camille Jan 31 '20 at 23:03
  • So: `ggplot(data.frame(x)) + geom_line(aes(x=x, y=y, color='distribution 1')) + geom_line(aes(x=x, y=y2, color='distribution 2')) + scale_color_manual(values = c("navy", "firebrick"))`. – Axeman Jan 31 '20 at 23:41

1 Answers1

0

You can repeat your x values twice, and put them under the same data frame with y1 and y2, this is the long format:

x = seq(-5,5,by=0.1)
y = dnorm(x,0,1)
y2 = dnorm(x,1,0.25)
dat = data.frame(
x = rep(x,2),
y = c(y,y2),
type = rep(c("distribution 1","distribution 2"),each=length(x))
)

ggplot(dat,aes(x=x,y=y,color=type)) +
  geom_line() +
  scale_color_manual(values=c("blue","red"))+
  labs(title ="Normal Distribution Curve & Normal CDF Curve ")

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72