R -分组条形图排序

时间:2021-10-17 05:39:17

Here is some R code and the graph it produces:

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

R -分组条形图排序

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.

注意,obj1在两个不同的日期出现两次,有两个不同的权重值。

1 个解决方案

#1


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

R -分组条形图排序

#1


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

R -分组条形图排序