r - R中的桑基图标签
问题描述
背景
我正在 R 中创建一个桑基图,我正在努力标记节点。
例如,我将重用一个包含 10 名假想患者的数据集,这些患者接受了 COVID-19 筛查。在基线时,所有患者的 COVID-19 均为阴性。假设 1 周后,所有患者再次接受检测:现在,3 名患者为阳性,6 名患者为阴性,1 名患者结果不确定。又过了一周,3名阳性患者仍为阳性,1名患者由阴性转为阳性,其他患者均为阴性。
data <- data.frame(patient = 1:10,
baseline = rep("neg", 10),
test1 = c(rep("pos",3), rep("neg", 6), "inconcl"),
test2 = c( rep(NA, 3), "pos", rep("neg", 6) ))
试图
要创建 Sankey 图,我使用的是ggsankey
包:
library(tidyverse)
#devtools::install_github("davidsjoberg/ggsankey")
df <- data %>%
make_long(baseline, test1, test2)
ggplot(df, aes(x = x, next_x = next_x, node = node, next_node = next_node,
fill = factor(node), label = node)) +
geom_sankey() +
geom_sankey_label(aes(fill = factor(node)), size = 3, color = "white") +
scale_fill_manual(values = c("grey", "green", "red")) +
theme(legend.position = "bottom", legend.title = element_blank())
问题
我想nodes
用每个节点中存在的患者数量来标记 (例如,第一个节点将被标记为10
,inconclusive
节点将被标记为1
,等等......)。
你如何在 R 中做到这一点而不对值进行硬编码?
部分解决方案
为了从数据中提取数字,我认为第一步应该是这样的:
data %>% count(baseline, test1, test2)
# baseline test1 test2 n
#1 neg inconcl neg 1
#2 neg neg neg 5
#3 neg neg pos 1
#4 neg pos <NA> 3
我认为,如果我能够在长数据的额外列中包含正确的值df
,我应该能够label=variable_name
从美学中调用?
解决方案
试试这个:
library(ggplot2)
library(ggsankey)
library(dplyr)
# create a count data frame for each node
df_nr <-
df %>%
filter(!is.na(node)) %>%
group_by(x, node)%>%
summarise(count = n())
#> `summarise()` has grouped output by 'x'. You can override using the `.groups` argument.
# join to sankey dataframe
df <-
df %>%
left_join(df_nr)
ggplot(df, aes(x = x, next_x = next_x, node = node, next_node = next_node,
fill = factor(node))) +
geom_sankey() +
geom_sankey_label(aes(label = node), size = 3, color = "white") +
geom_sankey_text(aes(label = count), size = 3.5, vjust = -1.5, check_overlap = TRUE) +
scale_fill_manual(values = c("grey", "green", "red")) +
theme_minimal()+
theme(legend.position = "bottom",
legend.title = element_blank())
数据
data <- data.frame(patient = 1:10,
baseline = rep("neg", 10),
test1 = c(rep("pos",3), rep("neg", 6), "inconcl"),
test2 = c( rep(NA, 3), "pos", rep("neg", 6) ))
df <- data %>%
make_long(baseline, test1, test2)
如果您想要一个边界框,您可以调整计数标签的位置或将其更改为标签(不太确定这是否有效)。不确定是否geom_sankey_label
识别check_overlap
以避免计数文本的多次重叠。
由reprex 包于 2021-04-20 创建 (v2.0.0 )
推荐阅读
- java - Spring 5,从 LDAP (AD) 获取信息
- python - 如何将 DataFrame 列拆分为多行?
- javascript - 等待值异步
- laravel - 在 laravel vapor signed-storage-url 中使用 Axios 默认值
- c++ - 读取多个结构并将其写入文件
- multithreading - 在多线程 C# WIndows Forms 应用程序中显示倒计时
- linux - Vfs_write 返回 EINVAL?
- angular - 如何以角度解析 url sanitizer 警告?
- php - 为什么我的代码打印出文本而不是变量的值?
- c# - Azure AD - 多个选项卡或浏览器 - 会话管理