簡體   English   中英

分組的ggplot2條形圖缺少錯誤條

[英]Grouped ggplot2 barplot with missing error bars

我試圖弄清楚如何只為組圖中的某些成員繪制誤差線。 例如,我有一個數據集定義為:

 new_frame <- data.frame(Parms = c("CAGR", "CAGR", "CAGR", 
                                   "CAGR", "CAGR", "DD", "DD",
                                   "DD","DD","DD"),
                         Values = c(28, 27.4, 26.9, 24.6, 27.9, 
                                    18.7, 19.2, 18.5, 19.2, 19.1),
                         Rebal = c(18, 19, 20, 21, 22,
                                   18, 19, 20, 21, 22),
                         sd = c(2.8, 2.3, 1.9, 2.9, 2.1, 0,0,0,0,0))

這給出了new_frame:

   Parms Values Rebal  sd
1   CAGR   28.0    18 2.8
2   CAGR   27.4    19 2.3
3   CAGR   26.9    20 1.9
4   CAGR   24.6    21 2.9
5   CAGR   27.9    22 2.1
6     DD   18.7    18 0.0
7     DD   19.2    19 0.0
8     DD   18.5    20 0.0
9     DD   19.2    21 0.0
10    DD   19.1    22 0.0

我的ggplot2語句是:

library(ggplot2)
ggplot(new_frame, aes(x=Rebal, y=Values, fill=Parms)) +
  geom_bar(position="dodge", stat="identity") + 
  geom_errorbar(aes(ymin=Values - sd, ymax=Values + sd),
  position=position_dodge(0.9), width=0.2) +
  ggtitle("           Variation With Rebalance Period”)

情節是:

缺少錯誤欄的示例

我的問題是如何避免繪制綠色條的空錯誤刻度。 在DD的sd值的new_frame中放入0仍會繪制刻度線,而將NA放入這些位置會引發ggplot錯誤。

您可以將geom_errorbar顏色的value == 0NA

ggplot(new_frame, aes(Rebal, Values, fill = Parms)) +
    geom_bar(position = "dodge", stat = "identity") + 
    geom_errorbar(aes(ymin = Values - sd, ymax = Values + sd,
                      # Is SD 0 (returns logical value)
                      color = sd == 0),
                  position = position_dodge(0.9), width = 0.2) +
    # Set 0 SD color to NA
    scale_color_manual(values = c("black", NA), guide = FALSE)

在此處輸入圖片說明

將0值設置為NA

# in the data
new_frame$sd[new_frame$sd == 0] = NA

# or inline 
aes(ymin = Values - ifelse(sd == 0, NA, sd), ymax = Values + ifelse(sd == 0, NA, sd))

默認情況下,這將引發警告。 您可以通過將參數na.rm = TRUE添加到geom_errorbar層來禁用警告:

geom_errorbar(
    aes(ymin = Values - sd, ymax = Values + sd),
    na.rm = T,
    position = position_dodge(0.9),
    width = 0.2
  )

我欣賞聰明的color = sd == 0方法,但這是一種更通用的方法,而不依賴於所使用的其他美學。 (例如,如果您為錯誤欄映射了color美學,那么您將需要為該工作方法選擇不同的美學。)

暫無
暫無

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

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