This question already has an answer here:
这个问题在这里已有答案:
- R stacked percentage bar plot with percentage of binary factor and labels (with ggplot) 1 answer
- R堆积的百分比条形图,具有二元因子和标签的百分比(带ggplot)1个答案
- geom_text position middle on a bar plot 1 answer
- geom_text位置中间的条形图1回答
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 = "")
I tried to add the labels with
我试着添加标签
geom_text(data = data_m, aes(x = Shop, y = value,
label = paste0((value/100) * 100,"%")), size=4)
但这会导致
EDIT: With JanLauGe's answer I get
编辑:有了JanLauGe的回答我得到了
Now, the percentages are wrongly assigned.
现在,错误地分配了百分比。
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?
另一句话:如果表的列总和不相同怎么办,比如上面的例子假设的91和107而不是100?
1 个解决方案
#1
3
Try this instead
试试这个
geom_text(data = data_m,
aes(x = Shop,
y = value / max(value),
label = paste0(value/100,"%")),
size = 4)
The problem: label position is relative to the plot area (0 to 1, 1 = max(value)
).
问题:标签位置是相对于绘图区域的(0到1,1 =最大值(值))。
The solution: rescale value accordingly.
解决方案:相应地重新调整值。
EDIT: Duplicate of this post.
编辑:这篇文章的重复。
What you are looking for is this:
你在寻找的是:
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()
#1
3
Try this instead
试试这个
geom_text(data = data_m,
aes(x = Shop,
y = value / max(value),
label = paste0(value/100,"%")),
size = 4)
The problem: label position is relative to the plot area (0 to 1, 1 = max(value)
).
问题:标签位置是相对于绘图区域的(0到1,1 =最大值(值))。
The solution: rescale value accordingly.
解决方案:相应地重新调整值。
EDIT: Duplicate of this post.
编辑:这篇文章的重复。
What you are looking for is this:
你在寻找的是:
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()