[英]How to order bars in a stacked barplot along with putting % labels
我数据的最小子集是
mydata <- read.table(header = TRUE, text= "
Product Characteristic Product_category
AA Functional A
AB Functional A
AB Portable A
BA Portable B
BA Quality B
BB Quality B
BA Bright B
BB Sound B
BB Sound B
BC Sound B
BC Sound B
BC Work B
CA Functional C
CA Functional C
CA Functional C
CA Functional C
CB Functional C
CC Functional C
CC Functional C
CC Functional C
CC Functional C
CC Portable C
CC Design C
CD Quality C
CD Quality C
CD Output C
CD Noise C
CD Noise C
CD Component C
CD Component C
")
我想用x = Characteristic和y轴对每个3个产品类别分别制作3个条形图。 此外,我想将栏与产品堆叠在一起。 因此,假设产品目录A的代码的代码是-
mydata %>% filter(Product_category == "A") %>%
ggplot(aes(x=Characteristic, fill = Product)) + geom_bar(width = 0.2) + coord_flip()
这部分很容易。 我在两件事上苦苦挣扎-我想按每个特征计数的降序对堆叠的条进行排序。 此数据集是我的数据集的最小子集,因此默认情况下,条形图可能显示为有序,但在我的实际数据集中却不是。 我想做的第二件事是用百分比标记每个条,这样百分比就在每个产品类别中-公式= count(Characteristic)/ sum(count(Characteristic))。 所以我希望我的最终图形看起来如下所示:
mydata %>% filter(Product_category == "A") %>%
group_by(Characteristic) %>%
summarize(counts = n()) %>% arrange(counts) %>%
mutate(Characteristic = factor(Characteristic, Characteristic), perc = counts/sum(counts)) %>%
ggplot(aes(x=Characteristic, y = counts)) +
geom_bar(stat = "identity", width = 0.4) +
theme(axis.text.x=element_blank()) +
geom_text(aes(label = paste(round(perc*100, digits = 1),"%",sep = "")), hjust = -0.2, size = 2.8, position = position_dodge(width = 0.7), inherit.aes = TRUE) +
coord_flip()
唯一的不同是,我希望每个栏按产品堆叠,因此我可以直观地看到每个产品在每个特征中的份额。 我尝试了许多事情,但每件事都很冗长,但仍然无法达到预期的效果。 最整洁的方法是什么?
您应该能够通过一点点dplyr
和dplyr
排序因素来执行此forcats
。 正如您所指出的那样,由于您要过滤的类别中没有很多观察结果,因此我进行了过滤只是为了说明更多数据,并且为了简化计算而跳过了图中的一些细节。例。 这样做的关键是将“ Characteristic
和“ Product
设置为因子,然后使用“ Product
来设置填充,因此您在每个特性内都有每个产品的堆叠区域。
您还可以简化其他几件事: geom_col
等效于geom_bar(stat = "identity")
,而scales::percent
将执行您拥有的百分比格式。 为了使文本出现在每个小节中,请使用position_stack
并使用vjust = 0.5
将标签居中。
library(tidyverse)
mydata %>%
# filter(Product_category == "A") %>%
group_by(Characteristic, Product) %>%
summarise(counts = n()) %>%
mutate(perc = round(counts / sum(counts), digits = 3)) %>%
ungroup() %>%
mutate(Characteristic = as.factor(Characteristic) %>% fct_reorder(counts, .fun = sum)) %>%
arrange(Characteristic, perc) %>%
mutate(Product = as.factor(Product) %>% fct_reorder(perc, .desc = F)) %>%
ggplot(aes(x = Characteristic, y = counts, fill = Product)) +
geom_col(position = "stack") +
geom_text(aes(label = scales::percent(perc)),
position = position_stack(vjust = 0.5), size = 3) +
coord_flip()
由reprex软件包 (v0.2.0)于2018-07-14创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.