Вот мое решение:
library("ggplot2")
library("dplyr")
library("magrittr")
library("tidyr")
df <- data.frame(x = c(1,1,2,3,2,1), y = c(43,54,54,22,22,43))
#Creating a counter that will keep track
#Of how many of each number in y exist for each x category
df$n <- 1
df %<>% #This is a bidirectional pipe here that overwrites 'df' with the result!
group_by(x, y) %>% #Unidirectional pipe
tally(n) %>%
mutate(n = round(n/sum(n), 2)) #Calculating as percentage
#Plotting
df %>%
ggplot(aes(fill = as.factor(y), y = n, x = x)) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = scales::percent) +
labs(y = "Percentage contribution from each y category") +
#Adding the percentage values as labels
geom_text(aes(label = paste0(n*100,"%")), position = position_stack(vjust = 0.5), size = 2)
Примечание : значения по оси Y представлены в процентах, потому что position="fill"
передается geom_bar()
.