简体   繁体   中英

R - Grouped Bar Plot Ordering Within Groups

Here is some R code and the graph it produces:

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")

在此输入图像描述

How do I ensure that the bars are sorted from highest to lowest (by weight ) within each individual group?

Note that obj1 appears twice, under two different dates, with two different weight values.

# 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")

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM