% mutate(team =-6ren">
gpt4 book ai didi

r - ggplot 订购聚集的条形图

转载 作者:行者123 更新时间:2023-12-04 10:20:27 25 4
gpt4 key购买 nike

重现我遇到的问题的代码:

library("data.table")
library("ggplot2")
DT<-data.table(team=c("Q1","Q2","Q3"), mon=c(3,5,2), tues=c(4,2,1), weds=c(4,2,5))
DT<-melt(DT,id.vars = "team", measure.name = c("mon","tues","weds"))
chartdata<-DT[,.(team, day=variable, score=value)]
ggplot(chartdata, aes(fill=day, y=score, x=team)) +#reorder(data3$Insurer, if(thisdir=="asc") {value} else {-value}))) +
geom_bar(position="dodge", stat="identity")

这会产生一个聚集的条形图。我需要按星期一的分数(降序)设置顺序,但看不到这样做的方法。我试过了:
ggplot(chartdata, aes(fill=day, y=score, x=reorder(team, {-score}))) + 
geom_bar(position="dodge", stat="identity")

但这似乎是对按星期一至星期三的总数测量的数据进行排序,而不是按照我的需要只使用星期一。

这可能吗?非常感谢!

最佳答案

您可以在绘图之前对数据框进行排序 ggplot2并固定用于 x 轴的变量的因子水平:

library(dplyr)
library(ggplot2)

chartdata %>%
arrange(day, -score) %>%
mutate(team = factor(team, unique(team))) %>%
ggplot(aes(x = team, y = score, fill = day))+
geom_col(position = position_dodge())

enter image description here

这是您要找的吗?

关于r - ggplot 订购聚集的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60889869/

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