如何在ggplot中结合ggdag显示DAG的自定义标签?
在ggplot中显示ggdag自定义标签的解决方案
问题场景
用户使用ggdag创建了带有自定义标签的DAG:
test <- dagify("a" ~ "b", "b" ~ "c", "c" ~ "d", "b" ~ "d", exposure = "b", outcome = "d", labels = c(a = "A", b = "B", c = "D"))
通过ggplot直接调用时,无法显示自定义标签:
test %>% ggplot(aes(x = x, y = y, xend = xend, yend = yend)) + geom_dag_point(color = "orange") + geom_dag_edges_arc(edge_color = "blue", curvature = 0) + geom_dag_text(color = "black") + theme_dag()
但使用ggdag(test, text = FALSE, use_labels = "label", edge_type = "link_arc")可以正常显示自定义标签,需要实现ggplot流程下的自定义标签显示。
解决方法
geom_dag_text()默认读取节点的name字段而非自定义的label字段,只需显式指定label映射即可:
方法1:修改geom_dag_text的映射
test %>% ggplot(aes(x = x, y = y, xend = xend, yend = yend)) + geom_dag_point(color = "orange") + geom_dag_edges_arc(edge_color = "blue", curvature = 0) + geom_dag_text(aes(label = label), color = "black") + # 显式绑定label列 theme_dag()
方法2:替换为geom_text
也可以直接用基础的geom_text(),同样指定label映射:
test %>% ggplot(aes(x = x, y = y, xend = xend, yend = yend)) + geom_dag_point(color = "orange") + geom_dag_edges_arc(edge_color = "blue", curvature = 0) + geom_text(aes(label = label), color = "black") + theme_dag()
原理:ggdag生成的DAG对象转化为数据框后,自定义标签存储在label列中,显式指定aes(label = label)就能让文本层调用你定义的标签内容。
内容的提问来源于stack exchange,提问作者pgcudahy
相关产品推荐
相关产品推荐

