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

Inf*_*911 4 plot r graph bar-chart ggplot2

这是一些 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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

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

Cyr*_*ian 6

# 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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明