2017-08-23 18 views
1

以下の関数を使用して欠損値をプロットしようとしています。ggplot2を使用して欠損値をプロットする

Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous. 
Error: Aesthetics must be either length 1 or the same as the data (65507): fill, x, y' 
library(reshape2) 
library(ggplot2) 
library(dplyr) 

ggplot_missing <- function(x){ 

    x %>% 
    is.na %>% 
    melt %>% 
    ggplot(data = ., 
      aes(x , 
       y)) + 
geom_raster(aes(fill = value)) + 
    scale_fill_grey(name = "", 
        labels = c("Present","Missing")) + 
    theme_minimal() + 
    theme(axis.text.x = element_text(angle=45, vjust=0.5)) + 
    labs(x = "Variables in Dataset", 
     y = "Rows/observations") 
} 

ggplot_missing(productholding) 

任意のアイデア:私は、このエラーメッセージが表示されますか?

+0

エラーメッセージがそれを言います - ベクトル値の長さは、1(すべて同じ値)またはシリーズの長さと同じである必要があります。 dfが正しく溶けているかどうか見てください... –

+0

再現可能な例を提供すると、他の人があなたを助けやすくなります。 – elevendollar

答えて

2

ggplotのxyは、ご使用の機能では指定されていません。私は、次にそれを変更:

ggplot_missing <- function(data){ 
    df2 <- data %>% is.na %>% melt 

    ggplot(df2, aes(Var2, Var1, fill=value)) + 
    geom_raster() + 
    scale_fill_grey(name="", labels=c("Present", "Missing")) + 
    theme_minimal() + 
    theme(axis.text.x = element_text(angle=45, vjust=0.5)) + 
    labs(x = "Variables in Dataset", 
     y = "Rows/observations") 
} 

テストデータ:

df <- iris 
set.seed(4) 
df[sample(nrow(df), 20), 2] <- NA 
df[sample(nrow(df), 30), 3] <- NA 
df[sample(nrow(df), 15), 4] <- NA 

ggplot_missing(df) 

enter image description here

+0

ありがとうございます:-)。これは役に立ちます。 – Que

0

OPの質問に若干のバリエーション。あなたが別の異なるレベルで各変数の欠損データのパターンを視覚化したい場合(因子)変数...

ggplot_missing2 <- function(data, xvar, yvars) { 
    # xvar should be a factor variable for this to work 
    require(ggplot2) 
    require(reshape2) 
    newvar = "variable" 
    newval = "value" 
    dl <- melt(data, id.vars = xvar, measure.vars=yvars, variable.name=newvar, value.name = newval) 
    dl <- dcast(dl, formula = as.formula(paste0(newvar,"~",xvar)), 
       fun.aggregate = function(x) sum(is.na(x))) 
    dl <- melt(dl, id.vars=newvar, variable.name=xvar, value.name=newval) 
    ggplot(dl, aes_string(x=xvar, y=newvar)) + 
    geom_tile(aes_string(fill=newval), color="white") + 
    geom_text(aes_string(label=newval)) + 
    scale_fill_continuous("Missing (N)", low="gray", high="cornflowerblue") + 
    labs(title="Missing Data Pattern") 
} 

テストデータ:

df <- iris 
set.seed(4) 
df[sample(nrow(df), 20), 2] <- NA 
df[sample(nrow(df), 30), 3] <- NA 
df[sample(nrow(df), 15), 4] <- NA 

ggplot_missing2(df) 

test data plot output from function

関連する問題