I have the following code, which generates a dataframe and plots a coord-flipped figure:
n <- 100
df <- data.frame(value = sample(1:5, size = n, replace = TRUE),
item = sample(c("Item1", "Item2", "Item3", "Item4"), size = n, replace = TRUE),
grp = sample(c("A", "B", "C"), size = n, replace = TRUE))
df_copy <- df %>% mutate(grp = "Total")
dplyr::bind_rows(df, df_copy) %>%
group_by(item, grp) %>%
summarise(mean = round(mean(value), 1)) %>%
mutate(tot = ifelse(grp == "Total", mean, NA)) %>%
group_by(item) %>%
mutate(tot = mean(tot, na.rm = TRUE)) %>%
ggplot(aes(x = reorder(item, tot), y = mean, group = grp, fill = grp)) +
geom_col(position = 'dodge') +
geom_text(aes(label = mean), position = position_dodge(width=0.9)) +
coord_flip()
Now, I have two problems:
- How can I change the order of the legend so that the 'Total' group is on top?
- How can I use
nudge_y
to plot the mean values on the right side of the bars?
Thank you!