如何绘制多条密度曲线并添加图例?
How do I plot multiple density curves and add a legend?
亲爱的群体智能。
我在尝试在一个 ggplot 对象中绘制不同的密度曲线并让它显示图例时遇到问题。
到目前为止我已经尝试了两种方法:
multiple_density <- ggplot() +
geom_density(data = df1, mapping = aes(x = df1$col1), color = "black") +
geom_density(data = df2, mapping = aes(x = df2$col1), color = "red") +
geom_density(data = df3, mapping = aes(x = df3$col1), color = "green") +
theme(legend.position = "right") +
scale_colour_manual(values = c("black" = "black", "red" = "red", "green" = "green"), name = "key") +
theme_classic()
并且:
combined_df <- bind_rows(df1, df2, df3, .id = "id")
multiple_density <- ggplot() +
geom_density(data = multiple_density, mapping = aes(x = combined_df$col1) +
theme(legend.position = "right") +
theme_classic()
在第一个代码中,我希望 scale_colour_manual
位可以解决问题,这是我之前在此类问题的答案中发现的,但这对我不起作用。
这里的问题可能是,不同的数据帧在它们各自的 col1
?
中没有相同数量的值
第二个代码没有给我 3 条不同的曲线,而是将 3 个数据帧中的所有值一起作为一条密度曲线,这显然是我不想要的。
我可能遗漏了一些明显的东西,但我们仍然会感谢您的帮助!
根据随机数据扩展我上面的评论:
library(tidyverse)
df1 <- tibble(col1=rnorm(500, mean=0))
df2 <- tibble(col1=rnorm(500, mean=2))
df3 <- tibble(col1=rnorm(500, mean=4))
df1 %>%
bind_rows(df2, df3, .id="DF") %>%
ggplot() +
geom_density(aes(x=col1, color=DF))
亲爱的群体智能。
我在尝试在一个 ggplot 对象中绘制不同的密度曲线并让它显示图例时遇到问题。
到目前为止我已经尝试了两种方法:
multiple_density <- ggplot() +
geom_density(data = df1, mapping = aes(x = df1$col1), color = "black") +
geom_density(data = df2, mapping = aes(x = df2$col1), color = "red") +
geom_density(data = df3, mapping = aes(x = df3$col1), color = "green") +
theme(legend.position = "right") +
scale_colour_manual(values = c("black" = "black", "red" = "red", "green" = "green"), name = "key") +
theme_classic()
并且:
combined_df <- bind_rows(df1, df2, df3, .id = "id")
multiple_density <- ggplot() +
geom_density(data = multiple_density, mapping = aes(x = combined_df$col1) +
theme(legend.position = "right") +
theme_classic()
在第一个代码中,我希望 scale_colour_manual
位可以解决问题,这是我之前在此类问题的答案中发现的,但这对我不起作用。
这里的问题可能是,不同的数据帧在它们各自的 col1
?
第二个代码没有给我 3 条不同的曲线,而是将 3 个数据帧中的所有值一起作为一条密度曲线,这显然是我不想要的。
我可能遗漏了一些明显的东西,但我们仍然会感谢您的帮助!
根据随机数据扩展我上面的评论:
library(tidyverse)
df1 <- tibble(col1=rnorm(500, mean=0))
df2 <- tibble(col1=rnorm(500, mean=2))
df3 <- tibble(col1=rnorm(500, mean=4))
df1 %>%
bind_rows(df2, df3, .id="DF") %>%
ggplot() +
geom_density(aes(x=col1, color=DF))