[英]R Stacked Bar Plot
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))
I am sincerely apologetic if this already was posted but I did not see it.如果这已经发布但我没有看到它,我深表歉意。 I wish to prepare a stacked bar plot there the X axis is 'Grade' and each Grade is 1 bar.
我希望准备一个堆叠条 plot X 轴是“等级”,每个等级是 1 条。 Every bar contains three color shades because there are three classes ('Class').
每个条都包含三种颜色阴影,因为存在三个类别(“类别”)。 Finally the height of the bar is 'Score' and it always starts from low class to high.
最后,条形的高度是“分数”,它总是从低 class 开始到高。 So it will look something like this but this is not to proper scale
所以它看起来像这样,但这不是适当的规模
We can use xtabs
to convert the data to wide format and then apply the barplot
我们可以使用
xtabs
将数据转换为宽格式,然后应用barplot
barplot(xtabs(Score ~ Grade + Class, data1), legend = TRUE,
col = c('yellow', 'red', 'orange'))
Or using ggplot
或使用
ggplot
library(dplyr)
library(ggplot2)
data1 %>%
mutate_at(vars(Grade, Class), factor) %>%
ggplot(aes(x = Grade, y = Score, fill = Class)) +
geom_col()
If we want to order for 'Class', convert to factor
with levels
specified in that order based on the 'Score' values如果我们要为“类”排序,请转换为基于“分数”值以该顺序指定的
levels
的factor
data1 %>%
mutate(Class = factor(Class, levels = unique(Class[order(Score)])),
Grade = factor(Grade)) %>%
ggplot(aes(x = Grade, y = Score, fill = Class)) +
geom_col()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.