I am trying to draw two density graphs on the same plot. I tried the following code.
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')
The code gives what I want. But I have to label x-axis and also need to add legends. How can I achieve this?
You should stack your two variables together and have a factor variable saying which column it is. Then you can add your labels and choose your colors like this:
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"))