r - ggplot 闪避条形图 : arrange bars by y-value per group

标签 r sorting ggplot2 geom-bar

我需要在 R 中绘制一个条形图,其中条形的顺序与下面的 data_frame 中的完全一样,即我需要左边的第 1 组,中间的 2 组和右边的 3 组。但是:我还需要在三组中按分数降序排列条形图,但我不知道该怎么做。

我已经按 'group' 和 'score' 对 data_frame 进行了排序,但是 ggplot 只采用了 'group' 变量的顺序:

data_scores <- data.frame(group = c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
               country = c("U", "D", "M", "D", "U", "M", "D", "M", "U"), 
               score = c(10, 7, 3, 15, 12, 4, 9, 7, 5))
ggplot(data_scores, mapping = aes(x = group, y = score, fill = country)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_text(aes(label = country),
            position=position_dodge(width=0.9), angle = 90, hjust = 1)

resulting plot

此代码按国家/地区对每个组内的条形图进行排序,但我需要按分数排列它们,就像第 3 组中的情况一样。

非常感谢您!

最佳答案

一种选择是使用由 groupcountry 的交互构成的辅助列。为此,我首先按 groupscore 排序,并使用 forcats::fct_inorder 设置辅助列和映射级别的顺序它在 group aes 上:

library(ggplot2)
library(dplyr)

data_scores <- data_scores |>
  arrange(group, desc(score)) |>
  mutate(group_order = forcats::fct_inorder(interaction(group, country)))

ggplot(data_scores, mapping = aes(x = group, y = score, fill = country, group = group_order)) +
  geom_col(position = position_dodge()) +
  geom_text(aes(label = country),
    position = position_dodge(width = 0.9), angle = 90, hjust = 1
  )

关于r - ggplot 闪避条形图 : arrange bars by y-value per group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72847638/

相关文章:

r - 如何在多个未分组的图中保持恒定的文本大小和 x 轴比例

r - 使用 ggplot2 y.axis.title 中的上标、粗体和颜色

r - 当新列名作为字符向量给出时,将数据分组到 `data.table` 中的好方法

sorting - 是否可以在 Julia 中对字典进行排序?

r - 如何在纵向数据集中进行 Winsorize(或删除单变量异常值)

c - 排序篮球运动员名字的函数

java - 一组到给定点的最近点

r - 如何更改使用ggplot2获得的图表条的颜色条

r - 将数字向量拆分为 R 中的连续 block

r - 如何在 R 中创建函数以从全局环境中删除除默认值和作为参数传递的对象之外的所有对象