How to suppress warnings when plotting with ggplot

前端 未结 3 919
感动是毒
感动是毒 2020-12-04 17:57

When passing missing values to ggplot, it\'s very kind, and warns us that they are present. This is acceptable in an interactive session, but when writing reports, you do no

相关标签:
3条回答
  • 2020-12-04 18:12

    A more targeted plot-by-plot approach would be to add na.rm=TRUE to your plot calls. E.g.:

      ggplot(mydf, aes(x = species)) + 
          stat_bin() + 
          geom_text(data = labs, aes(x = species, y = value, 
                                     label = value, vjust = -0.5), na.rm=TRUE) +
          facet_wrap(~ lvl)
    
    0 讨论(0)
  • 2020-12-04 18:21

    You need to suppressWarnings() around the print() call, not the creation of the ggplot() object:

    R> suppressWarnings(print(
    + ggplot(mydf, aes(x = species)) + 
    +    stat_bin() + 
    +    geom_text(data = labs, aes(x = species, y = value, 
    +                               label = value, vjust = -0.5)) +
    +    facet_wrap(~ lvl)))
    R> 
    

    It might be easier to assign the final plot to an object and then print().

    plt <- ggplot(mydf, aes(x = species)) + 
       stat_bin() + 
       geom_text(data = labs, aes(x = species, y = value,
                                  label = value, vjust = -0.5)) +
       facet_wrap(~ lvl)
    
    
    R> suppressWarnings(print(plt))
    R> 
    

    The reason for the behaviour is that the warnings are only generated when the plot is actually drawn, not when the object representing the plot is created. R will auto print during interactive usage, so whilst

    R> suppressWarnings(plt)
    Warning message:
    Removed 1 rows containing missing values (geom_text).
    

    doesn't work because, in effect, you are calling print(suppressWarnings(plt)), whereas

    R> suppressWarnings(print(plt))
    R>
    

    does work because suppressWarnings() can capture the warnings arising from the print() call.

    0 讨论(0)
  • 2020-12-04 18:27

    In your question, you mention report writing, so it might be better to set the global warning level:

    options(warn=-1)
    

    the default is:

    options(warn=0)
    
    0 讨论(0)
提交回复
热议问题