在直方图中显示带填充的类别比例

时间:2015-11-02 00:20:53

标签: r ggplot2

我正在尝试制作类似于此示例的直方图:

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 个答案:

答案 0 :(得分:1)

你需要把它作为一个因素。 weight也不是有效的美学映射。

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