如何在ggplot2中使用directlabels标记线

unhi4e5o  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(157)
library(ggplot2)
library(directlabels)
mydat <- structure(list(Name = c("Ana", "Josh", "Bart", "Ana", "Josh", 
"Bart"), color_line = c("purple", "purple", "orange", "purple", 
"purple", "orange"), x = c(0.864864864864865, 0.810810810810811, 
0.472972972972973, 0.851351351351351, 0.702702702702703, 0.648648648648649
), y = c(0.702702702702703, 0.675675675675676, 0.797297297297297, 
0.797297297297297, 0.72972972972973, 0.635135135135135), Class = c("A", 
"A", "A", "B", "B", "B")), class = c("data.table", "data.frame"
), row.names = c(NA, -6L))

mydat
   Name color_line         x         y Class
1:  Ana     purple 0.8648649 0.7027027     A
2: Josh     purple 0.8108108 0.6756757     A
3: Bart     orange 0.4729730 0.7972973     A
4:  Ana     purple 0.8513514 0.7972973     B
5: Josh     purple 0.7027027 0.7297297     B
6: Bart     orange 0.6486486 0.6351351     B

我有上面的数据集,并将结果绘制如下:

g <- ggplot(mydat, aes(x = x, y = y, color = Class)) + 
       theme_classic() + 
       geom_line(mapping = aes(group = Name), color = mydat$color_line) + 
       geom_point() + 
       scale_color_manual(values=c("springgreen4", "royalblue3"))
g

现在,我想把每个人的Name添加到每一行,看起来像这样:

我找到的最接近的东西是library(directlabels)中的angled.boxes。你可以看到它看起来是here
但是,当我尝试下面的时候,我得到了一个不同的情节。

direct.label(g, "angled.boxes")

2w3rbyxf

2w3rbyxf1#

一个实现你想要的结果的选择是使用geomtextpath包,它增加了很多选项来添加直接的标签到行,甚至允许弯曲的文本。对于你的用例,你可以简单地用geomtextpath::geom_textline替换geom_line来添加你的标签。
注意:另外,我稍微调整了代码,使用color aes绘制线条,使用fill aes为点着色。

library(ggplot2)
library(geomtextpath)

pal_color <- c("purple", "purple", "orange")
names(pal_color) <- c("Ana", "Josh", "Bart")

pal_fill <- c("springgreen4", "royalblue3")
names(pal_fill) <- c("A", "B")

base <- ggplot(mydat, aes(x = x, y = y)) + 
  scale_color_manual(values = pal_color) +
  scale_fill_manual(values= pal_fill) +
  theme_classic() +
  guides(color = "none")

base +
  geomtextpath::geom_textline(
    aes(group = Name, color = Name, label = Name), textcolour = "black") +
  geom_point(aes(fill = Class), shape = 21, stroke = 0, size = 2)

或者使用offsetgap参数,您可以在行的顶部添加标签:

base +
  geomtextpath::geom_textline(
    aes(group = Name, color = Name, label = Name),
    offset = unit(5, "pt"), gap = FALSE, textcolour = "black") +
  geom_point(aes(fill = Class), shape = 21, stroke = 0, size = 2)

hc2pp10m

hc2pp10m2#

这并不理想,但我很久以前就这样做了,使用一些数学和手动调整

mydat %>% 
  group_by(Name) %>% 
  mutate(
    posx = mean(x)*1.01,
    posy = mean(y)*1.01,
    angle = -60*diff(range(y))/diff(range(x))
    ) %>% 
  ggplot(aes(x = x, y = y, color = Class)) + theme_classic() +
  geom_line(mapping = aes(group = Name), color = mydat$color_line) +
  geom_point() + scale_color_manual(values=c("springgreen4", "royalblue3"))+
  geom_text(aes(x = posx, y = posy, group = Name, label = Name, angle = angle),
            size = 6, show.legend = FALSE, color = "black")

相关问题