簡體   English   中英

ggplot2 使用堆疊條時帶有誤差條的條形圖

[英]ggplot2 barplots with errorbars when using stacked bars

我正在嘗試生成一個帶有誤差條的堆疊條形圖,該條形圖表示每個條形的總可變性。 我不想使用躲避條形圖,因為每個條形有 >10 個類別。

下面我有一些可重現示例的示例數據:

scenario = c('A','A','A','A')
strategy = c('A','A','A','A')
decile = c(0,0,10,10)
asset = c('A','B','A','B')
lower = c(10,20,10, 15)
mean = c(30,50,60, 70)
upper = c(70,90,86,90)
data = data.frame(scenario, strategy, decile, asset, lower, mean, upper)

一旦我們有了data df 我們就可以使用 ggplot2 來創建一個堆疊的條形,如下所示:

ggplot(wide, aes(x=decile, y=mean, fill=asset)) + 
  geom_bar(stat="identity") +
  facet_grid(strategy~scenario) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.25)

但是,產生的誤差條是針對每個堆疊條的每個單獨組件的:

在此處輸入圖片說明

我很欣賞我為 df 的每一行提供lowermeanupper結果,但即使我按十分位數對這些求和,我也沒有在每個條形堆棧的頂部得到我想要的誤差條。

什么是正確的 ggplot2 代碼,或者,啟用此功能的正確數據結構是什么?

我認為你意識到你需要操縱你的數據而不是你的情節是正確的。 您不能在誤差條上真正擁有position_stack ,因此您需要重新計算誤差條的均值、上限值和下限值。 本質上,這意味着獲得平均值的累積總和,並相應地移動上限和下限。 您可以在dplyr管道內執行此dplyr

請注意,我認為您還需要在誤差條上設置position_dodge ,因為即使適當移動它們的范圍也會重疊,這將使它們更難在視覺上解釋:

library(ggplot2)
library(dplyr)

data %>% 
  mutate(lower = lower - mean, upper = upper - mean) %>%
  group_by(decile) %>% 
  arrange(rev(asset), by.group = TRUE) %>%
  mutate(mean2 = cumsum(mean), lower = lower + mean2, upper = upper + mean2) %>%
  ggplot(aes(x = decile, y = mean, fill = asset)) + 
  geom_bar(stat = "identity") +
  facet_grid(strategy ~ scenario) +
  geom_errorbar(aes(y = mean2, ymin = lower, ymax = upper), width = 2,
                position = position_dodge(width = 2)) +
  geom_point(aes(y = mean2), position = position_dodge(width = 2))

在此處輸入圖片說明

如果每個十分位數只需要一個誤差條,則應聚合這些值,以便這樣的資產之間沒有差異:

library(ggplot2)
library(dplyr)
#Code
data %>% group_by(scenario,decile) %>% 
  mutate(nlower=mean(lower),nupper=mean(upper)) %>%
  ggplot(aes(x=factor(decile), y=mean, fill=asset,group=scenario)) + 
  geom_bar(stat="identity") +
  facet_grid(strategy~scenario) +
  geom_errorbar(aes(ymin = nlower, ymax = nupper), width = 0.25)

輸出:

在此處輸入圖片說明

使用資產是另一回事,因為它會考慮每個類,因為您對每個類都有不同的值:

#Code 2
data %>%
  ggplot(aes(x=factor(decile), y=mean, fill=asset,group=scenario)) + 
  geom_bar(stat="identity") +
  facet_grid(strategy~scenario) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.25)

輸出:

在此處輸入圖片說明

在上一個版本中,每個資產都有自己的誤差條,但是如果您想在全局范圍內查看錯誤,您應該使用一種聚合限制的方法,就像使用平均值或其他您希望的度量一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM