2016-08-24 209 views
2

我想着色虛線,它們是兩個相應的類別的平均值,具有相同的顏色由ggplot使用默認調色板的填充分佈:顏色平均線ggplot

Click here to view the distribution

這是所使用的代碼:

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) 
) 

謝謝大家提前!

回答

0

沒有重複的例子,但你可能想要做這樣的事情:

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) 

這種做法擴展到任意數量的組。

不需要預先計算的,但也有點更哈克的選項,就是:

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']))) 
+0

謝謝你,第二個選項運作良好;但我不得不刪除一個額外的傳說出現[如何關閉一些傳說](http://stackoverflow.com/questions/14604435/turning-off-some-legends-in-a-ggplot) –