0

I want to add letters next to the bars as shown in the excel bar graph.

enter image description here

I have used this code and got this result

horiz <- 9.38
quux <- data %>%
  select(Genotype,Specie, Pn, pn1) %>%
  arrange(desc(Pn)) %>%
  mutate(Genotype = factor(Genotype, levels = Genotype))

ggplot(quux, aes(Genotype, fill=Specie)) +
  geom_rect(aes(xmin=as.numeric(Genotype)-0.4, xmax=as.numeric(Genotype) + 0.4, 
        ymin=pmax(horiz, Pn), ymax=pmin(horiz, Pn)))+
  scale_x_discrete() + scale_y_continuous(breaks = seq(6.95, 12.41, 0.9))+ 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))+
  geom_hline(yintercept = 9.38, linetype = "dashed", color = "black")+
  geom_text(aes(label = Genotype, y = horiz), angle=90, hjust = 1.1) + 
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) + 
  geom_text(data = data, aes(y = Pn+0.2, label = pn1),position = position_dodge(width = .75))

enter image description here

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    We (still) don't have your `data`, so it's speculation. Assuming that the problem is that the letters added below `horiz` should be "outside" the bars, then perhaps `aes(y = ifelse(Pn – r2evans Aug 23 '23 at 13:46
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Aug 23 '23 at 14:16
  • @MrFlick thanks for suggestion, i will consider it next time. – Ikram Bashir Aug 23 '23 at 17:55
  • @r2evans it worked but some of the letter are overlapping with the labels of the bars. Is there any way could I adjust the letters of selective bars? – Ikram Bashir Aug 23 '23 at 17:57
  • Perhaps `ifelse(Pn > horiz, Pn + 0.2, pmin(7.85, Pn - 0.2))`? That deals with overlaps with the larger (rotated) text labels, though not necessarily with each other. – r2evans Aug 23 '23 at 18:08

0 Answers0