我知道已經有關于這個的問題,但我的情況不同,我不知道該怎么做。
在我的 tibble 中,有一列“values”,每個觀察值都有一個值,“ind”將觀察結果分成大小相等的兩組,“average_time”包含觀察值所屬組的平均值。
這是我為獲取圖表而撰寫的代碼:
my_data %>% ggplot(aes(values, x=ind, fill=ind))
geom_bar(stat="summary", fun=mean)
theme_minimal()
theme(legend.position="none")
我得到這張圖:

現在我想將每個欄底部的類別從第 1 部分和第 2 部分更改為“第 1 組”和“第 2 組”,但我找不到方法。
另外,我想在條形圖中添加平均值。換句話說,我想在條內以白色顯示每個條的值,如下所示:

誰能幫我這個?
uj5u.com熱心網友回復:
也許這個?
library(ggplot2)
my_data %>%
ggplot(aes(ind, values, fill = ind))
geom_bar(stat = "summary", fun = mean)
geom_text(stat = "summary", fun = mean, aes(label = stat(y)),
vjust = 2, size = 12, color = "white")
scale_x_discrete(labels = c("Group 1", "Group 2"), name = "Group")
scale_fill_brewer(palette = "Set1")
theme_minimal(base_size = 20)
theme(legend.position = "none")

使用的資料
my_data <- data.frame(values = c(100.1, 52.5), ind = c("part1", "part2"))
uj5u.com熱心網友回復:
如果您在不止一層中使用計算,則預先計算并將其輸入 ggplot2 可能更簡單:
library(dplyr); library(ggplot2)
mtcars %>%
group_by(gear = as.character(gear)) %>%
summarize(avg_mpg = mean(mpg)) %>%
ggplot(aes(x=gear, y=avg_mpg, fill=gear))
geom_col()
geom_text(aes(label = round(avg_mpg)), vjust = 1.5, color = "white")
scale_x_discrete(labels = c(
"3" = "Group 3",
"4" = "Group 4",
"5" = "Group 5"))
theme_minimal()
theme(legend.position="none")

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/527522.html
上一篇:PCA雙圖中載荷的不同顏色
