简体   繁体   中英

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)?

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM