我有以下代码,它生成一个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
在条形图的右侧绘制平均值?
谢谢大家!
1条答案
按热度按时间mnemlml81#
使用
factor
s进行排序,使用hjust
将文本移动一点。