我想制作一個類似于這個的條形圖,來自

非常感謝任何幫助修復我的代碼的線索。
uj5u.com熱心網友回復:
問題是geom_bar正在為您構建直方圖,因此無法訪問資料框中的所有其他列。這里我使用geom_col自己構建直方圖,包括計算每組的總計數和標準差。
另一種選擇(df2,下面的第二個圖)是mutate用 a替換summarize,并將其作為單獨的資料幀傳遞給geom_errorbar(并保留您的geom_bar)。我更喜歡這個,因為它只為每個條繪制一次誤差線,而不是為每種顏色過度繪制它們。
library(dplyr, warn.conflicts = FALSE)
library(ggplot2)
df <- diamonds %>% group_by(clarity, color) %>%
summarize(count = n()) %>%
group_by(clarity) %>%
mutate(sd = sqrt(var(count)), count_total = sum(count)) %>%
ungroup()
#> `summarise()` has grouped output by 'clarity'. You can override using the `.groups` argument.
ggplot(df, aes(clarity, y=count, fill=color, ymin=count_total-sd, ymax = count_total sd))
geom_col()
geom_errorbar()

df2 <- diamonds %>% group_by(clarity, color) %>%
summarize(count = n()) %>%
group_by(clarity) %>%
summarize(sd = sqrt(var(count)), count_total = sum(count)) %>%
ungroup()
#> `summarise()` has grouped output by 'clarity'. You can override using the `.groups` argument.
ggplot(diamonds, aes(clarity, fill=color))
geom_bar()
geom_errorbar(data = df2, aes(clarity, ymin=count_total-sd, ymax = count_total sd), inherit.aes = FALSE)

由reprex 包(v2.0.1)于 2021 年 10 月 10 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315851.html
下一篇:在R中將多個圖連接在一起
