我需要在 R 中繪制一個條形圖,其中條形圖的順序與下面的 data_frame 中的完全一樣,即我需要左側的組 1、中間的組和右側的組 3。但是:我還需要在三組中按分數降序排列,我不知道該怎么做。
我已經按“組”和“分數”對 data_frame 進行了排序,但 ggplot 只采用了“組”變數的順序:
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 組就是這種情況。
非常感謝您!
uj5u.com熱心網友回復:
一種選擇是使用由 和 的互動組成的輔助group
列country
。為此,我首先按group
and排序,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
)
uj5u.com熱心網友回復:
好吧,您可以分別生成條形圖和文本幾何圖形,然后再將它們相加。不是很漂亮,但有效:
reorder_group <- function(df, fn) {
df %>%
group_by(group) %>%
group_map(function(x, ...) {
x %>%
mutate(country = reorder(country, score, decreasing = TRUE)) %>%
fn()
}, .keep = TRUE)
}
g_col <-
data_scores %>%
reorder_group(function(df) geom_col(data = df, position = position_dodge()))
g_text <-
data_scores %>%
reorder_group(function(df) {
geom_text(
aes(label = country),
data = df,
position = position_dodge(width = 0.9), angle = 90, hjust = 1
)
})
g_main <- ggplot(data_scores, aes(x = group, y = score, fill = country))
reduce(c(g_col, g_text), ` `, .init = g_main)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/498296.html
上一篇:如何避免重復插入sqlite