MeC
MeC

Reputation: 463

Conditonally add labels to ggplot stacked barplot

This is similar to previous questions, but I haven't found a solution that works yet.

I have a stacked barplot in ggplot almost exactly like the one listed here. Like that user, I only want category labels for those bars with a count > 20. I tried to do the subset solution suggested there as well as an ifelse statement. For the subset solution I get:

    Error in n > 20 : comparison (6) is possible only for atomic and list types

My graph:

data %>% 
      count(groups, Response) %>%
      mutate(group = factor(groups)) %>% 
      ggplot(aes(groups, n, fill=Response)) + 
      geom_col(aes(fill = Response)) +
      geom_text(data=subset(data, n>20), aes(label=n), position=position_stack(0.5), size = 3)

I don't know if sharing my data would be useful, but I can do that if necessary.

Upvotes: 0

Views: 136

Answers (1)

Axeman
Axeman

Reputation: 35307

Your data does not contain n, only your piped in anonymous data does, after the count function. Here are three solutions:

1.

data %>% 
      count(groups, Response) %>%
      mutate(group = factor(groups)) %>% 
      {
        ggplot(., aes(groups, n, fill=Response)) + 
        geom_col(aes(fill = Response)) +
        geom_text(data=filter(., n>20), aes(label=n), position=position_stack(0.5), size = 3)
       }

2.

counts <- data %>% 
      count(groups, Response) %>%
      mutate(group = factor(groups))

ggplot(counts, aes(groups, n, fill=Response)) + 
      geom_col(aes(fill = Response)) +
      geom_text(data=filter(counts, n>20), aes(label=n), position=position_stack(0.5), size = 3)

3.

data %>% 
      count(groups, Response) %>%
      mutate(group = factor(groups)) %>% 
      ggplot(aes(groups, n, fill=Response)) + 
      geom_col(aes(fill = Response)) +
      geom_text(data=. %>% filter(n>20), aes(label=n), position=position_stack(0.5), size = 3)

Upvotes: 1

Related Questions