我有一个简单的数据框,它分别有一个 id 是真假的概率:
library(tidyverse)
dat <- data.frame(id = "999", real = 0.7, fake = 0.3)
我知道我可以使用以下代码将其显示为水平条形图:
dat %>%
gather(key = grp, value = prob, -id) %>%
ggplot(aes(x = id, y = prob, fill = grp)) +
geom_bar(stat = "identity") +
coord_flip()
但我想知道是否有一种方法可以以如下所示的相同方式显示这一点,在条形图的两端都有类标签和概率?
非常感谢
答案 0 :(得分:2)
一个直接的,也许有点厚颜无耻的解决方法是重新定义你的 0。
我添加了一些并非绝对必要的调用,但使其看起来更接近您的示例图。
library(tidyverse)
dat <- data.frame(id = "999", real = -0.7, fake = 0.3) # note the minus sign!
dat %>%
gather(key = grp, value = prob, -id) %>%
ggplot(aes(x = id, y = prob, fill = grp)) +
geom_col(show.legend = FALSE) +
geom_text(aes(label = stringr::str_to_title(paste0(grp, " (", as.character(100*abs(prob)), "%)"))),
hjust = c(1,0))+
coord_flip(clip = "off") +
scale_fill_brewer(palette = "Greys") +
theme_void() +
theme(aspect.ratio = .1,
plot.margin = margin(r = 3, l = 3, unit = "lines"))
由 reprex package (v0.3.0) 于 2021 年 2 月 6 日创建
答案 1 :(得分:1)
我不确定这是否完全回答了问题,但我认为它会改善情节,您可以尝试一下吗?
dat %>%
gather(key = grp, value = prob, -id) %>%
ggplot(aes(x = id, y = prob, fill = grp)) +
geom_bar(stat = "identity", position = "fill") +
scale_y_continuous("Proportion") +
scale_x_discrete("", expand = c(0,0)) +
scale_fill_identity() +
coord_flip()