I made a heatmap using ggplot2
package. I want to add some text on the top of the graph using the annotate
function. For some reason the text were "covered" by some portions. What can I do to show the full label?
The sample data is like this:
data <- data.frame("group" = c("grp1", "grp2", "grp3", "grp4"), "pct" = runif(100, min = 0, max = 100))
data <- data %>%
group_by(group) %>%
mutate(id = row_number())
Code for graph is like this:
ggplot(data, aes(x=id, y=group, fill = pct)) +
geom_tile() +
theme_minimal() +
annotate("text", x = 3, y = 4.7, size = 3.2,label = "Morning") +
annotate("text", x = 7, y = 4.7, size = 3.2,label = "Afternoon") +
annotate("text", x = 12, y = 4.7, size= 3.2, label = "Evening") +
annotate("text", x = 17, y = 4.7, size = 3.2, label = "Night") +
theme(plot.margin = unit(c(0.3, 0.45, 0.3, 0.45), "cm"))
The figure is attached here.
You can see that the morning, afternoon, evening, and night text could not be displayed fully. I tried adding the margins using the plot.margin
command, but did not work. Any idea on how to fix that?
Thanks!!
plot.margin
sets the margins around the outside of the plot, whereas you need to make more space inside the plot. @Camille has the right idea: you need to expand the y-axis. Luckily it's simple: just pass theexpand
argument toscale_y_discrete
.expand
just adds extra space to the sides of the axis, so it doesn't matter that your data is discrete (unlike usingylim
). If you want to define the extra space in more detail (for example, to only add space to the top), passingexpand_scale
to theexpand
argument (thanks @Camille!) lets you define the extra space on each of the 4 sides individually. It also lets you add either an absolute or relative amount of space. The syntax is a bit weird, so check?expand_scale
to see the argument names: