Home > Software design >  Position labels when they are overlapping in a stacked bar chart
Position labels when they are overlapping in a stacked bar chart

Time:01-01

I have been working in a couple of stacked bar plots, but some of bins are too small to fit the label, resulting in overlapping, unreadable labels. See the graph below:

enter image description here

Please consider the MWE below, which generated the above graph.

Q: Is it possible to add lines from the labels pointing to where the bars are? So that they are offset and more readable?

 tribble(
~parm, ~value,
"b1", 0.009,
"g1", 0.664,
"b2", 0.000,
"ra", 0.000,
"rc", 0.000,
"ax", 0.084,
"cx", 0.086,
"ex", 0.179,
"ay", 0.045,
"cy", 0.043,
"ey", 0.102
) -> doc1


 
 
doc2 <- tribble(
  ~parm, ~value,
  "b1", 0.181,
  "g1", 0.289,
  "b2", 0.181,
  "ra", 0.000,
  "rc", 0.000,
  "ax", 0.001,
  "cx", 0.001,
  "ex", 0.002,
  "ay", 0.001,
  "cy", 0.001,
  "ey", 0.002,
  "re", 0.000,
  "rf", 0.000,
  "b3", 0.289
)


doc1 <- doc1 %>% mutate(model = "exp")
doc2 <- doc2 %>% mutate(model = "exp2")


finalpow <- doc1 %>% full_join(doc2)


# Make a stacked bar plot
ggplot(finalpow, aes(x = model, y = value, fill = parm))  
  geom_bar(stat = "identity", color = "black")  
    geom_text(aes(label = parm), position = position_stack(vjust = 0.5))  
  theme_luis()  
  theme(axis.text.x = element_text(angle = 90, hjust = 1))  
  labs(x = "Parameter", y = "Variance explained in NCP", fill = "Parameter")  
  scale_y_continuous()  
  coord_flip()

CodePudding user response:

As @Camille already suggested in the comments, you can use the ggrepel with geom_text_repel function and replace it with geom_text. You can play with max.overlaps if you want. Here is some reproducible code:

library(dplyr)
library(ggplot2)
library(ggrepel)
doc1 <- doc1 %>% mutate(model = "exp")
doc2 <- doc2 %>% mutate(model = "exp2")

finalpow <- doc1 %>% full_join(doc2)
#> Joining, by = c("parm", "value", "model")

# Make a stacked bar plot
ggplot(finalpow, aes(x = model, y = value, fill = parm))  
  geom_bar(stat = "identity", color = "black")  
  geom_text_repel(aes(label = parm), position = position_stack(vjust = 0.5))  
  theme(axis.text.x = element_text(angle = 90, hjust = 1))  
  labs(x = "Parameter", y = "Variance explained in NCP", fill = "Parameter")  
  scale_y_continuous()  
  coord_flip()

Created on 2022-12-24 with reprex v2.0.2


Please check the link above for a lot of more great examples with this package.

  • Related