R - 在组内排序的分组条形图

时间:2017-02-14 02:02:09

标签: r plot graph ggplot2 bar-chart

这是一些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值。

1 个答案:

答案 0 :(得分:4)

# 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