堆叠条形图,带有百分比值的标签条 [英] Stacked bar plot, label bars with percentage values
本文介绍了堆叠条形图,带有百分比值的标签条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将表格绘制为堆积的条形图,并用百分比标记条形.这是一个示例:
I want to plot a table as a stacked bar plot and label the bars with the percentages. Here is an example:
data <- matrix(c(34, 66, 22, 78), ncol = 2)
data <- as.table(data)
colnames(data) <- c("shop1", "shop2")
rownames(data) <- c("prod1", "prod2")
library(reshape2)
data_m <- melt(data, varnames = c("Product", "Shop"), id.vars = "Product")
library(scales)
library(ggplot2)
ggplot(data_m, aes(x = Shop, y = value, fill = Product)) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = percent_format()) +
labs(x = "", y = "")
我尝试添加标签
geom_text(data = data_m, aes(x = Shop, y = value,
label = paste0((value/100) * 100,"%")), size=4)
但这会导致
有了JanLauGe的回答,我得到了
With JanLauGe's answer I get
现在,错误地分配了百分比.
Now, the percentages are wrongly assigned.
另一句话:如果表的列总和不同,该如何处理,比如说91和107,而不是我上面的示例中假定的100,该怎么办?
Another remark: what to do if the column sums of the table were not the same, say 91 and 107 instead of 100 as assumed in my above example?
推荐答案
尝试尝试
geom_text(data = data_m,
aes(x = Shop,
y = value / max(value),
label = paste0(value/100,"%")),
size = 4)
问题:标签位置相对于绘图区域(0到1,1 = max(value)
).
The problem: label position is relative to the plot area (0 to 1, 1 = max(value)
).
解决方案:相应地重新调整值.
The solution: rescale value accordingly.
编辑:此帖子的副本.
您正在寻找的是这个
ggplot(data = data_m,
aes(x = Shop,
y = value,
fill = Product,
cumulative = TRUE)) +
geom_col() +
geom_text(aes(label = paste0(value/100,"%")),
position = position_stack(vjust = 0.5)) +
theme_minimal()
这篇关于堆叠条形图,带有百分比值的标签条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文