0

I have a problem connected with one once discussed. This example R: ggplot stacked bar chart with counts on y axis but percentage as label I used few months ago to generate this kind of plot:

library(ggplot2)
library(dplyr)

df <- as.data.frame(matrix(nrow = 7, ncol= 3,
                   data = c("ID1", "ID2", "ID3", "ID4", "ID5", "ID6", "ID7",
                            "north", "north", "north", "north", "south", "south", "south",
                            "A", "B", "B", "C", "A", "A", "C"),
                  byrow = FALSE))




colnames(df) <- c("ID", "region", "species")


ggplot(df %>% count(region, species) %>%    # Group by region and species, then count number in each group
     mutate(pct=n/sum(n)),              # Calculate percent within each region
   aes(region, n, fill=species)) +
  geom_bar(stat="identity") +
  geom_text(aes(label=paste0(sprintf("%1.1f", pct*100),"%")), 
        position=position_stack(vjust=0.5))

Everything worked well. But now if i run the same code, i get a plot like this:

Myplot

Have anybody had similar problem? Thanks in advance!

J_F
  • 9,956
  • 2
  • 31
  • 55
  • 2
    Not knowing any context, what *is* your question/problem? – Maurits Evers Dec 07 '17 at 09:32
  • Note to add `group_by(region)` to get the desired output. Until now you will have the overall percentage and not the percentage per region. `df %>% group_by(region) %>% count(region, species) %>% # Group by region and species, then count number in each group mutate(pct=n/sum(n)` if you read the comments exactly, you see the group_by command ... but it was missed in the code – J_F Dec 07 '17 at 09:42
  • Thanks a lot! It helped! But I can't understand why the same code (without group_by) worked well few months ago. Can it be possible that I had some ohter version/ ohter package in addition so the group_by wasn't neccesary?! I've tried very many ways to detect the reason, but without results... – Liis Simmul Dec 07 '17 at 18:47

0 Answers0