gpt4 book ai didi

R 堆积条形图

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

data1=data.frame("Grade"=c(1,1,1,2,2,2,3,3,3),
"Class"=c(1,2,3,1,2,3,1,2,3),
"Score"=c(6,9,9,7,7,4,9,6,6))

如果已经发布但我没有看到它,我真诚地道歉。我希望准备一个堆叠条形图,其中 X 轴为“等级”,每个等级为 1 个小节。每个条形都包含三种颜色深浅,因为存在三个类 ('Class')。最后,栏的高度是“分数”,它总是从低级到高级。所以它看起来像这样,但这不是适当的规模

enter image description here

最佳答案

我们可以使用 xtabs将数据转换为宽格式,然后应用 barplot

barplot(xtabs(Score ~ Grade + Class, data1), legend = TRUE,
col = c('yellow', 'red', 'orange'))

或使用 ggplot
library(dplyr)
library(ggplot2)
data1 %>%
mutate_at(vars(Grade, Class), factor) %>%
ggplot(aes(x = Grade, y = Score, fill = Class)) +
geom_col()

enter image description here

如果我们要订购“Class”,请转换为 factorlevels根据“分数”值按该顺序指定
data1 %>% 
mutate(Class = factor(Class, levels = unique(Class[order(Score)])),
Grade = factor(Grade)) %>%
ggplot(aes(x = Grade, y = Score, fill = Class)) +
geom_col()

关于R 堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61047591/

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