I need to label each bar from d_ranked_long
(height = rank) with its rank's absolute value in d_long$value
, so I added geom_text(data = d_long, aes(x=parameter, label=value))
to the ggplot
at the end but got this error.
Error in `f()`:
! Aesthetics must be valid data columns. Problematic aesthetic(s): y = rank.
Did you mistype the name of a data column or forget to add after_stat()?
Backtrace:
1. base `<fn>`(x)
2. ggplot2:::print.ggplot(x)
4. ggplot2:::ggplot_build.ggplot(x)
5. ggplot2 by_layer(function(l, d) l$compute_aesthetics(d, plot))
6. ggplot2 f(l = layers[[i]], d = data[[i]])
7. l$compute_aesthetics(d, plot)
8. ggplot2 f(..., self = self)
With the geom_text()
command, as solved here How to put labels over geom_bar in R with ggplot2, I'm telling R: with each (x,y) in d_long_ranked
, grab the value
in the corresponding position in d_long
and put it on top of the bar. For example, the first bar in the first panel (vs = 0, am = 0) should have 3.44 on top of it, the second bar in the first panel should have 8.00 on top of it, and so on.
sample data
d_wide <- head(mtcars) %>%
rownames_to_column(var = "make_model") %>% select(!c(make_model,gear, carb))
absolute values in long format
d_long <- d_wide %>%
pivot_longer(!c(vs, am), names_to = "parameter", values_to = "value")
Save the ranks in a separate dataframe
d_ranked <- data.frame(d_wide [,c(8:9)],
t(apply(d_wide[,-c( 8:9)], 1,
rank, ties.method='min')))
the ranks in long format
d_ranked_long <- d_ranked %>%
pivot_longer(!c(vs, am), names_to = "parameter", values_to = "rank")
The x-axis ticks need to be in the following order:
d_ranked_long$parameter <- factor(d_ranked_long$parameter, levels = c("wt", "cyl", "drat", "hp",
"disp", "qsec","mpg"))
d_long$parameter <- factor(d_long$parameter, levels = c("wt", "cyl", "drat", "hp",
"disp", "qsec","mpg"))
put everything together
d_ranked_long %>%
ggplot(aes(x=parameter, y=rank)) +
geom_bar(stat = "identity") +
geom_text(data = d_long, aes(x=parameter, label=value)) +
facet_grid(am ~ vs) +
theme(axis.text.x = element_text(angle = 90))