rggplot2

Overlapping labels in legend in ggplot?


How to avoid overlapping the legend labels in ggplot?

enter image description here

ggplot(g3, aes(variable, country, fill= value)) + geom_tile() +
theme(axis.text.y = element_text(size = 15), axis.text.x = element_text(angle = 45, hjust = 1, size = 15), legend.position="bottom", legend.text = element_text(size = 15, angle = 50),
     axis.title.x = element_blank(),axis.title.y = element_blank())

Solution

  • For axis labels, the best way to fix this is to use the ggplot2::guide_axis() function, which will adjust both the angle and vertical/horizontal positioning at the same time. You can also make your legend labels easier to read by scaling the label. This might obviate the need to rotate the legend labels. For example:

    library(ggplot2)
    ggplot(g3, aes(variable, country, fill = value)) + 
      geom_tile() +
      labs(x = "", y = "") +
      scale_fill_continuous(labels = scales::label_number(scale = 10000, suffix = "k")) +
      guides(x = guide_axis(angle = 45), fill = guide_colorbar(direction = "horizontal)) +
      theme(legend.position = "bottom", text = element_text(size = 15))