【问题标题】:R - Grouped Bar Plot Ordering Within GroupsR - 组内分组条形图排序
【发布时间】:2017-07-02 04:20:36
【问题描述】:

这是一些 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")

如何确保每个组中的条形图从最高到最低(按weight)排序?

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

【问题讨论】:

    标签: r plot graph ggplot2 bar-chart


    【解决方案1】:
    # 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-02
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多