我需要在 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)
此代码按国家/地区对每个组内的条形图进行排序,但我需要按分数排列它们,就像第 3 组中的情况一样。
非常感谢您!
最佳答案
一种选择是使用由 group
和 country
的交互构成的辅助列。为此,我首先按 group
和 score
排序,并使用 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/