I'm trying to do a horizontal, stacked bar chart. I want to label each part of the bar with the corresponding number (count). Those labels appear twice and I don't now why. How can I make "92" etc. appear only once?
Code:
library(ggplot2)
library(dplyr)
library(plyr)
data2 <- data.frame(System=rep(c('participants opinion'), each=5),
attitude=rep(c('totally agree','agree somewhat','unsure','disagree somewhat','totally disagree'), times=2),
count=c(92, 83, 22, 17, 6))
data2$attitude = factor(data2$attitude, levels = c('unsure','totally disagree','disagree somewhat','agree somewhat','totally agree'))
data2 = arrange(data2, System, desc(attitude))
data2 = ddply(data2, .(System), transform, pos = (cumsum(count) - 0.5 * count))
cbPalette <- c("#999999", "#2A7AD4", "#5C96D7", "#D3A253", "#D48F1D")
ggplot(data2, aes(x = factor(System), y = count, fill = attitude))
geom_bar(stat = "identity", width = .3)
geom_text(aes(y = pos, label = count), size = 4)
coord_flip()
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.y = element_blank())
scale_fill_manual(values=cbPalette)
CodePudding user response:
your data2
object has 2 rows for every count, if you remove one row of each by:
label_data <- data2 |>
split(~count) |>
purrr::map_dfr(~.x |> head(1))
and putting it into:
geom_text(data = label_data, aes(y = pos, label = count), size = 4)
you can avoid that