我正在尝试获得一个堆积的条形图,其中有测试A和B的AUC的差异
样本数据:
df <- data.frame(test=rep(c("testA","testB"),2), AUC=c(0.8,0.9,0.6,0.3), reader=rep(c("reader1","reader2"),each=2))
我尝试过的事情
我知道如何计算差异并分配颜色。
df %>%
spread(test,AUC) %>%
group_by(reader) %>%
mutate(dif=testA-testB) %>%
gather(key,value,testA:testB) %>%
mutate(color=case_when(is.negative(dif)~"green",TRUE~"red")) -> df
我哪里失败了
我不完全知道如何使用ggplot2获取堆积图
必须类似:
ggplot(df,aes(x=reader,y=value, fill=color...
答案 0 :(得分:3)
我认为这就是您想要的:
library(tidyverse)
这是问题中的数据框,我只是以不同的方式创建了它,并为计算进行了有意的考虑。
data.frame(
test = factor(rep(c("testA", "testB"), 2), levels = c("testA", "testB")),
AUC = c(0.8, 0.9, 0.6, 0.3),
reader = rep(c("reader1", "reader2"), each = 2),
stringsAsFactors = FALSE
) -> xdf
现在,我们:
testA
AUC geom_col()
testA
位于底部通过以下方式完成
:group_by(xdf, reader) %>%
arrange(test) %>%
summarise(
diff = diff(AUC),
testA_auc = AUC[1]
) %>%
gather(measure, value, -reader) %>%
mutate(color = case_when(
measure == "diff" & (sign(value) == -1) ~ "Decrease with Test B",
measure == "diff" & (sign(value) > -1) ~ "Increase with Test B",
measure == "testA_auc" ~ "Test A"
)) %>%
mutate(
color = factor(
x = color,
levels = c("Test A", "Increase with Test B", "Decrease with Test B")
)
) %>%
mutate(value = abs(value)) %>%
ggplot(aes(reader, value, fill = color)) +
geom_col(position = position_stack(reverse = TRUE)) +
scale_y_continuous("Estimated AUC", limits = c(0, 1)) +
scale_x_discrete("Reader", labels = c("1", "2")) +
scale_fill_manual(
name = NULL,
values = c(
"Test A" = "#2166ac",
"Increase with Test B" = "#5aae61",
"Decrease with Test B" = "#b2182b"
)
) +
hrbrthemes::theme_ipsum_rc(grid = "Y")