2017-02-14 15 views
3

Вот некоторые R код и график он производит:R - Сгруппированный Bar Plot Заказ в группах

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