2017-02-14 72 views
3

下面是一些R代码里面和图形它产生:的R - 分组条形图排序中的组

library(ggplot2) 
year <- c("1950", "1950", "1960", "1960", "1970", "1970") 
weight <- c(15, 10, 20, 25, 18, 20) 
name <- c("obj1", "obj2", "obj3", "obj4", "obj5", "obj1") 
object.data <- data.frame(year, weight, name) 
ggplot(object.data, aes(x=factor(year), y=weight, 
    fill=reorder(name, -weight))) + geom_bar(stat="identity", position="dodge") 

enter image description here

如何确保棒进行排序,从最高到最低(由weight )在每个个人小组内?

请注意obj1在两个不同的日期出现两次,两个不同的值为weight

回答

3
# Create a new variable with your desired order. 
object.data1 = object.data %>% 
    group_by(year) %>% 
    mutate(position = rank(-weight)) 

# Then plot 
ggplot(object.data1, 
    aes(x=year, y=weight, fill=reorder(name, -weight), group = position)) + 
    geom_bar(stat="identity", position="dodge") 

enter image description here