2

I would like to colour the dashed lines, which are the average values of the two respective categories, with the same colour of the default palette used by ggplot to fill the distributions:

Click here to view the distribution

This is the code used:

library(ggplot2)

print(ggplot(dati, aes(x=ECU_fuel_consumption_L_100Km_CF, fill=Model))
  + ggtitle("Fuel Consumption density histogram, by Model")
  + ylab("Density")
  + geom_density(alpha=.3)
  + scale_x_continuous(breaks=pretty(dati$ECU_fuel_consumption_L_100Km_CF, n=10))
  + geom_vline(aes(xintercept = mean(ECU_fuel_consumption_L_100Km_CF[dati$Model == "500X"])), linetype="dashed", size=1)
  + geom_vline(aes(xintercept = mean(ECU_fuel_consumption_L_100Km_CF[dati$Model == "Renegade"])), linetype="dashed", size=1)
)

Thank you all in advance!

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
Gerard.Ill
  • 31
  • 3

1 Answers1

0

No reproducible example, but you probably want to do something like this:

library(dplyr)
# make up some data
d <- data.frame(x = c(mtcars$mpg, mtcars$hp),
                var = rep(c('mpg', 'hp'), each = nrow(mtcars)))
means <- d %>% group_by(var) %>% summarize(m = mean(x))

ggplot(d, aes(x, fill = var)) +
  geom_density(alpha = 0.3) +
  geom_vline(data = means, aes(xintercept = m, col = var), 
             linetype = "dashed", size = 1)

This approach is extendable to any number of groups.

An option that doesn't require pre-calculation, but is also a bit more hacky, is:

ggplot(d, aes(x, fill = var)) +
  geom_density(alpha = 0.3) +
  geom_vline(aes(col = 'hp', xintercept = x), linetype = "dashed", size = 1,
             data = data.frame(x = mean(d$x[d$var == 'hp']))) +
  geom_vline(aes(col = 'mpg', xintercept = x), linetype = "dashed", size = 1,
             data = data.frame(x = mean(d$x[d$var == 'mpg'])))
Axeman
  • 32,068
  • 8
  • 81
  • 94
  • Thank you, the second option worked well; but I had to remove an additional legend appeared [how to turn off some legends](http://stackoverflow.com/questions/14604435/turning-off-some-legends-in-a-ggplot) – Gerard.Ill Aug 24 '16 at 18:50