I don't know about doing it with base graphs (i.e. barplot
) but you can do it with ggplot2
with a combination of geom_bar
and geom_text
. Here is an example:
library(tibble)
library(ggplot2)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df <- tribble(
~x, ~fraction, ~group,
"not_exempt", 0.08, "med_assist",
"not_exempt", 0.04, "hospitilized",
"exempt", 0.09, "med_assist",
"exempt", 0.08, "hospitilized"
)
df %>%
mutate(x = factor(x)) %>%
ggplot(aes(x = x, y = fraction, fill = group)) +
geom_bar(stat = "identity", position = "dodge") +
geom_text(aes(y = fraction + 0.001, label = fraction,
x = if_else(group == "hospitilized", as.numeric(x) - 0.2, as.numeric(x) + 0.2)))
#> Warning: package 'bindrcpp' was built under R version 3.4.4
Created on 2018-09-08 by the reprex package (v0.2.0).