gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:09:42 24 4
gpt4 key购买 nike

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

最佳答案

# 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

关于R - 分组条形图在组内排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42216633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com