使用 geom_dl() 重叠标签

RKe*_*thL 5 label r ggplot2 geom-text

我的线图很合适,只是我的标签重叠太多。我意识到它们各自的数据点很接近,但是有没有办法美化标签间距?

我的数据和代码:

library(ggplot2)
library(directlabels) #geom_dl

#Original df
df <- data.frame(names=c('AAAA', 'BBBB', 'CCCC', 'DDDD', 'EEEE'),SP22=c(57, 30, 27, 35, 34),FA22=c(52, 38, 31, 34, 31),SP23=c(49, 32, 30, 29, 31))

#df to long format
longdf <- melt(df, id='names')

last.bumpup <- list("last.points","bumpup")

#lineplot
longdf %>%
ggplot() + 
  geom_line(aes(x=variable, y=value, group=names, color=names)) +
  scale_y_continuous(n.breaks=6, limits=c(20, 60)) +
  scale_color_manual(values=c("darkred", "steelblue","black", "coral1", 
                              "darkorchid2")) +
  geom_dl(aes(x=variable, y=value,label=names, color= names),
          method="last.bumpup", cex=0.8) +
  labs(title = "Comparison of...") + 
  xlab(label = "Terms") +
  ylab(label = "Numbers") +
  #scale_colour_discrete(guide="none") +
  theme_minimal() +
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

我需要在代码中添加/更改什么才能实现更漂亮的标签定位?预先致以诚挚的谢意。

pha*_*man 5

一种选择是使用geom_label_repelfrom ggrepel。如果您预先对要标记的点进行子集化,那么这样做会更容易。

library(ggrepel)

label.sub <- longdf[longdf$variable=="SP23",]

#lineplot
longdf %>%
  ggplot() + 
  geom_line(aes(x=variable, y=value, group=names, color=names)) +
  scale_y_continuous(n.breaks=6, limits=c(20, 60)) +
  scale_color_manual(values=c("darkred", "steelblue","black", "coral1", 
                              "darkorchid2")) +
  geom_label_repel(data=label.sub, aes(x=variable, y=value, label=names, colour=names), 
                   hjust=0, direction="y", segment.colour = "lightgrey", nudge_x = 0.1) +
  labs(title = "Comparison of...") + 
  xlab(label = "Terms") +
  ylab(label = "Numbers") +
  #scale_colour_discrete(guide="none") +
  theme_minimal() +
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

您还可以使用各种参数来获得所需的间距 - 有关详细信息,请参阅文档。简而言之,nudge_x用于距行端的左/右间距,以及box.padding每个标签周围的空间。


All*_*ron 5

geom_textline另一种选择是使用geomtextpath 包中的直接标记:

library(geomtextpath)

longdf %>%
  ggplot(aes(variable, value, group = names, colour = names)) + 
  geom_textline(aes(label = names, hjust = names), spacing = 200) +
  scale_hjust_manual(values = c(0.1, 0.4, 0.1, 0.6, 0.3)) +
  scale_y_continuous(n.breaks = 6, limits = c(20, 60)) +
  scale_color_manual(values = c("darkred", "steelblue","black", "coral1", 
                                "darkorchid2"), guide = "none") +
  labs(title = "Comparison of...", x = "Terms", y = "Numbers") + 
  theme_minimal() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述