Home > Software design >  How to avoid overlaying annotations?
How to avoid overlaying annotations?

Time:04-27

I'm trying to plot some annotation in a geom_histogram() ggplot. See image below. These annotations are the count of the histogram for each bin, each group. However, I don't know how to distance the different annotations when the counts are similar. I only know to fix the annotation with vjust or hjust but I wonder if there's a relative way. I don't think an example is necessary. Probably just looking at my code will be easy for someone more experienced.

This is the code I have used:

bind_rows(
  RN_df %>% mutate(type='RN'),
  RVNM_df %>% mutate(type='RVM')
) %>% group_by(hash) %>% 
  summarise(n_eps = n(), genre, type) %>% 
  ggplot(aes(x = n_eps, fill = genre))  
  geom_histogram(binwidth = 1)  
  stat_count(aes(y=..count..,label=..count.., colour = genre),geom="text",vjust= -1, hjust = 0.5, size = 3)  
  facet_wrap(~type)

This is my output image:

histogram

CodePudding user response:

You can use geom_text_repel from ggrepel:

library(ggrepel)

ggplot(df, aes(x = n_eps, fill = genre))  
  geom_histogram(binwidth = 1)  
  geom_text_repel(aes(label = ..count..), stat = 'count', 
            position = position_stack(vjust = 0.5), direction = 'y')  
  facet_wrap(~type)

enter image description here

  • Related