0

I have plotted three different posterior distribution on the same figure and I want to add a label to clarify posterior distribution 1, posterior distribution 2 and posterior distribution 3. I have tried to use '''scale_colour_manual''' but it does not work. Could you please do me a favor? Really appreciate it.

x <- seq(-10, 15, 0.01)

# Prior Distribution 
w1 <- 0.6; w2 <- 0.2; w3 <- 0.2
# p(x)
d1 <- dnorm(x, mean=4, sd=2)
d2 <- dnorm(x, mean=6, sd=3)
d3 <- dnorm(x, mean=5, sd=2)
p_x <- w1*d1+w2*d2+w3*d3

# Posterior distribution
p1 <- d1*w1/p_x
p2 <- d2*w2/p_x
p3 <- d3*w3/p_x
df <- data.frame(x, p1, p2, p3)

# Plot with ggplot
library(ggplot2)
ggplot(df, aes(x)) +
   geom_line(aes(y=p1), color='red')+
   geom_line(aes(y=p2), color='blue')+
   geom_line(aes(y=p3), color='black')+
   ylab('the Posterior Distribution')+
   scale_colour_manual("Groups", values = c("red", "blue", "black"))

enter image description here

Fox_Summer
  • 149
  • 6

1 Answers1

1

Solution 1

You can use the col argument inside aes() with de name of each distribution, and define the colors in scale_colour_manual

ggplot(df, aes(x)) +
  geom_line(aes(y=p1,col = "Dist. 1"))+
  geom_line(aes(y=p2,col = "Dist. 2"))+
  geom_line(aes(y=p3,col = "Dist. 3"))+
  ylab('the Posterior Distribution')+
  scale_colour_manual("Groups", values = c("red", "blue", "black"))

enter image description here

Solution 2

You can pivot your data.frame, making one column for the values and another for the distributions

df %>% 
  pivot_longer(cols = -x) %>% 
  ggplot(aes(x,value,col = name)) +
  geom_line()+
  ylab('the Posterior Distribution')+
  scale_colour_manual("Groups", values = c("red", "blue", "black"))

enter image description here

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32