在密度图上标记并添加图例

label and add legends on density plot

我想在同一个地块上绘制两个密度图。我尝试了以下代码。

car     Bus
48.1    17.8
47.2    21.2
69.9    27
72.7    9.1
73.8    23.9
67.7    4.9
61.1    12.3
61.6    0.4
        4.7
        20.9
        5.5
        19.8
         5.9
        14.3
        16.3


 library(ggplot2)
m <-ggplot()+geom_density(aes(data$column1),color='red')+geom_density(aes(data$column2), color='blue') 

代码给出了我想要的。但我必须标记 x 轴,还需要添加图例。我怎样才能做到这一点?

您应该将两个变量叠加在一起,并有一个因子变量说明它是哪一列。然后您可以添加标签并选择颜色,如下所示:

data <- read.table(text = "
column1 column2
48.1    17.8
47.2    21.2
69.9    27
72.7    9.1
73.8    23.9
67.7    4.9
61.1    12.3
61.6    0.4
NA        4.7
NA        20.9
NA        5.5
NA        19.8
NA         5.9
NA        14.3
NA        16.3", header = TRUE)
plot.data <- data.frame(x      = c(data$column1, data$column2),
                        column = paste("column", rep(c(1:2), each = nrow(df))))
library(ggplot2)
m <-ggplot(plot.data, aes(x = x, fill = column)) + geom_density(alpha = 0.5) +
  xlab("My x label") + ylab("My y label") +
  scale_fill_manual(name = "My legend title", values = c("red", "blue"))