show text on top of graph (ggplot2)

2020-04-20 22:03发布

问题:

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!!

回答1:

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 the expand argument to scale_y_discrete.

expand just adds extra space to the sides of the axis, so it doesn't matter that your data is discrete (unlike using ylim). If you want to define the extra space in more detail (for example, to only add space to the top), passing expand_scale to the expand 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:

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") +
    scale_y_discrete(expand = expand_scale(mult = c(0, 0.3)))



标签: r ggplot2 text