IamWarmduscher
IamWarmduscher

Reputation: 955

How do I adjust the position of plot labels in R using ggplot?

Given then the following dataframe and plot:

year = c(2007, 2008, 2009, 2010, 2011, 2012)
pc = c(-.17, .0115, -.049, -.0116, -0.059, -.155)
df_test = data.frame(year, pc)

df_test %>%
  ggplot(aes(x=year, y=pc, label=pc)) +
  geom_line() +
  geom_text()

year_pc_plot

You can see that the labels interfere with the plot. I've tried to manually adjust the labels using geom_text(hjust=0, vjust=-1, size=3) but this takes a while to get it right.

Is there a way to have the plot labels automatically position themselves above/below or left/right (or alternating above/below left/right)?

Upvotes: 0

Views: 772

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

Here's a fairly concise and appealing way of drawing this kind of plot:

df_test %>%
  ggplot(aes(x=year, y=pc, label=pc)) +
  geom_line() +
  geom_label(fill = "gray92", label.size = NA)

enter image description here

Upvotes: 1

Related Questions