2017-08-25 33 views
1

我有一個通用的plot_data(data)方法。有時,輸入的數據有我用填寫變量所有NAS,這將導致錯誤ggplot2錯誤,當填充值都是NA:seq.default(h [1],h [2],length.out = n)中的錯誤:

Error in seq.default(h[1], h[2], length.out = n) : 
    'to' must be a finite number 

例如:

df <- data.frame(
    x = c(1, 2, 3, 4), 
    y = c(10, 15, 20, 25), 
    foo = factor(c(NA, NA, NA, "yes"), levels=c("yes", "no")) 
) 

ggplot(df, aes(x=x, y=y, fill=foo))+geom_bar(stat = "identity") # works 
ggplot(df[1:3, ], aes(x=x, y=y, fill=foo))+geom_bar(stat = "identity") # error 

我不明白爲什麼情節不應該渲染在情況2(只有全部灰色條)。有沒有簡單的方法來克服這一點?

回答

1

的難吃類...

ggplot(df[1:3,], aes(x=x, y=y, if(!all(is.na(foo))){fill=foo})) + 
    geom_bar(stat = "identity") 
0

灰色表示不填充。例如,下面的人會產生灰色拉絲:

ggplot(df, aes(x=x, y=y))+geom_bar(stat = "identity") 在你的榜樣,當包括與foo = "yes"行,與foo = NA行實際上不是充滿了色彩,只有最後一排裝滿。但是,如果排除最後一行,則列foo中的所有值將變爲NA。如錯誤所示,填充映射中的to的末尾必須是有限數字,而不是NA。規避這種情況的方法是將NA轉換成字符串,如:

ggplot(df[1:3, ], aes(x=x, y=y, fill=ifelse(is.na(foo), "NA", foo)))+geom_bar(stat = "identity")

2

您可以使用fct_explicit_naforcats包,使缺失值一個明確的因子水平。 (注意:addNA從基礎包不會在這裏工作;後者增加了NA的水平,但不會導致它在圖中顯示。)

ggplot(df[1:3, ], 
     aes(x=x, y=y, fill=forcats::fct_explicit_na(foo)))+ 
    geom_bar(stat = "identity") 

旁白:如果你有其他的值&只需要不同的默認顏色,您可以更改scale_fill_discrete(na.value = "some colour other than grey")的選項