0

By running this code :

    g <- ggplot(results_table_TR, aes(x = Criteria, 
                               y = Pct*100,
                               fill=column_names)) + 
  geom_bar( stat = "identity", width = 0.5, position="dodge") + 
  scale_color_manual(values = Palcolor) +
  scale_fill_manual(values = Palcolor) +
  theme_classic() + 
  theme(legend.position = "bottom", 
        legend.title      = element_blank(), 
        axis.line.x=element_blank(), 
        axis.line.y=element_blank(), 
        axis.ticks.x = element_blank(), 
        axis.ticks.y = element_blank(),
        axis.text.y = element_blank(),
        legend.key.height = unit(0.3, "lines"), 
        legend.key.width  = unit(0.7, "lines"),
        legend.box.margin = margin(t = -10, b = 0, l = 40, unit='pt'),
        plot.title = element_text(size=16,  hjust = 0.5),
        axis.text.x = element_text(margin = margin(t = -0.5, unit = "cm"), size = 8),
        legend.text       = element_text(margin = margin(r = 40, unit = "pt"))) +
  guides(fill = guide_legend(nrow = 1, byrow = TRUE)) + 
  xlab("") + 
  ylab("") + 
  ggtitle(gTitle) + 
  geom_text(aes(label = paste0(sprintf("%0.1f", round(Pct*100, digits = 1)),"%"), vjust = -0.8, 
                hjust = 0.5), size = 2.9, color = "black") + 
  scale_x_discrete(labels = function(Criteria) str_wrap(Criteria, width = 18))

I got this graphic : enter image description here As you can see, the labels (percentages) are all aligned vertically by group of bars, but not by bar.Howa can I correct ?

  • 3
    Try adding `position = "dodge"` in your `geom_text` call – Allan Cameron Jun 25 '20 at 14:39
  • For text you likely need to list the amount of dodge; `position = position_dodge(width = .9)`. See the "aligning labels and bars" section in the Examples in the help page for `geom_text()` for more complete info. – aosmith Jun 25 '20 at 14:50
  • You may also need to supply a `group=` aesthetic. For text, it's not always clear for `ggplot` on which column it should use for dodging, so adding `group=column_names` into the `aes()` for `geom_text()` would also fix that. – chemdork123 Jun 25 '20 at 14:58
  • Allon Cameron. Thansk for you reply, but position = 'dodge' is already in the code. – Jacques Troussart Jun 26 '20 at 05:37
  • @JacquesTroussart It doesn't look like you've got `position = 'dodge'` in the *`geom_text`* layer (not `geom_bar`), which is what everyone above is referring to. – Z.Lin Jun 30 '20 at 07:15

0 Answers0