I would like to extend the question posted here:
Create stacked barplot where each stack is scaled to sum to 100%, of a scattered barplot with an argument of geom_bar
set to position = "fill"
.
library(ggplot2)
library(dplyr)
library(tidyr)
dat <- read.table(text = " ONE TWO THREE
1 23 234 324
2 34 534 12
3 56 324 124
4 34 234 124
5 123 534 654",sep = "",header = TRUE)
# Add an id variable for the filled regions and reshape
datm <- dat %>%
mutate(ind = factor(row_number())) %>%
gather(variable, value, -ind)
ggplot(datm, aes(x = variable, y = value, fill = ind)) +
geom_bar(position = "fill",stat = "identity") +
# or:
# geom_bar(position = position_fill(), stat = "identity")
scale_y_continuous(labels = scales::percent_format())
Imagine you would like to add segment labels. It works for me if I leave out position = "fill",
(even though it messes up the y-axis scale).
ggplot(datm, aes(x = variable, y = value, fill = ind)) +
geom_bar(stat = "identity") +
# or:
# geom_bar(position = position_fill(), stat = "identity")
scale_y_continuous(labels = scales::percent_format())+
geom_text(label= 'bla')
but, if I add position = "fill",
the plot is messed up. The bars disappear as they are marginalized to for scale of up to 100, and the labels appear detached from bars in the grey area.
ggplot(datm, aes(x = variable, y = value, fill = ind)) +
geom_bar(position = "fill", stat = "identity") +
# or:
# geom_bar(position = position_fill(), stat = "identity")
scale_y_continuous(labels = scales::percent_format())+
geom_text(label= 'bla')
Why? How to? Thx!