R语言 图例项的更改顺序

dsekswqp  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(224)

我有以下代码,它生成一个dataframe并绘制一个坐标翻转图:

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()

现在我有两个问题

  • 如何更改图例的顺序,使“总计”组位于顶部?
  • 如何使用nudge_y在条形图的右侧绘制平均值?

谢谢大家!

mnemlml8

mnemlml81#

使用factor s进行排序,使用hjust将文本移动一点。

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()

相关问题