问题
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)
but this results in
EDIT: With JanLauGe's answer I get
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?
回答1:
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)
).
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()
来源:https://stackoverflow.com/questions/43065409/stacked-bar-plot-label-bars-with-percentage-values