2015-11-02 52 views
0

我試圖使類似於此示例直方圖:類別比例與填充

enter image description here

這裏是我的代碼:

data <- structure(list(Group = c(23L, 18L, 23L, 2L, 7L, 2L, 7L, 2L, 19L, 24L, 19L, 2L, 19L, 2L, 19L, 2L, 19L, 18L, 3L, 19L), Weight = c(0.0111111111111111, 0.0111111111111111, 0.142857142857143, 0.142857142857143, 0.0666666666666667, 0.0666666666666667, 0.0666666666666667, 0.0666666666666667, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037, 0.0037037037037037), 
    Distance = c(187.499584053076, 187.499584053076, 10.6737766469012, 
    10.6737766469012, 281.336385978512, 281.336385978512, 253.13100905741, 
    253.13100905741, 251.437995888686, 251.437995888686, 237.356329723974, 
    237.356329723974, 250.386230871559, 250.386230871559, 368.035367705982, 
    368.035367705982, 356.508544839761, 356.508544839761, 469.363999574087, 
    469.363999574087)), .Names = c("Group", "Weight", "Distance" 
), row.names = c(NA, 20L), class = "data.frame") 

mdata = melt(data, id=c('Weight','Group')) 

ggplot(mdata, aes(x=value, weight = Weight, fill=Group)) + 
geom_bar(position="fill") 

我似乎無法成爲能夠告訴ggplot使用Group作爲顏色。什麼是正確的方法來做到這一點?

回答

1

您需要使其成爲一個因素。另外weight不是有效的美學映射。

mdata$Group = factor(mdata$Group) 
ggplot(mdata, aes(x=value, fill=Group)) + 
    geom_bar(position="fill")