0

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!

D. Studer
  • 1,711
  • 1
  • 16
  • 35
  • 2
    (1) ggplot2/axis-order: https://stackoverflow.com/q/3253641/3358272, https://stackoverflow.com/q/12774210/3358272, https://stackoverflow.com/q/18401931/3358272; ordering with groups https://stackoverflow.com/q/44350031/3358272. (2) `geom_text(..., position = position_nudge(y = -0.1))`, from `?position_nudge`, though breaks your `position_dodge` ... instead use `hjust=`. – r2evans Mar 22 '23 at 14:37

1 Answers1

1

Use factors for ordering and hjust for moving text over a little.

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)) %>%
  mutate(grp = relevel(factor(grp), "Total")) %>%
  ggplot(aes(x = reorder(item, tot), y = mean, group = grp, fill = grp)) +
  geom_col(position = 'dodge') +
  geom_text(aes(label = mean), hjust = -0.1, position = position_dodge(width=0.9)) +
  coord_flip()

ggplot with text moved and legend reordered

r2evans
  • 141,215
  • 6
  • 77
  • 149