在 R 中为三种不同的后验分布添加带有 ggplot 的标签
Add a label with ggplot in R for three different posterior distributions
我在同一张图上绘制了三种不同的后验分布,我想添加一个标签来阐明后验分布 1、后验分布 2 和后验分布 3。我尝试使用 '''scale_colour_manual'' ' 但它不起作用。你能帮我一个忙吗?非常感谢。
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"))
解决方案 1
您可以在 aes()
中使用 col
参数和每个分布的名称,并在 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"))
解决方案 2
您可以旋转 data.frame,为值制作一列,为分布制作另一列
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"))
我在同一张图上绘制了三种不同的后验分布,我想添加一个标签来阐明后验分布 1、后验分布 2 和后验分布 3。我尝试使用 '''scale_colour_manual'' ' 但它不起作用。你能帮我一个忙吗?非常感谢。
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"))
解决方案 1
您可以在 aes()
中使用 col
参数和每个分布的名称,并在 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"))
解决方案 2
您可以旋转 data.frame,为值制作一列,为分布制作另一列
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"))