Search code examples
rstatisticsgraphing

Add statistical information to the bottom of a graph


I am try to add statistical information (min, max, quartile values, mean, median etc) regarding a given distribution to the bottom a graph (histogram, time series plot) in R. I know the stats can be generated using the summary() function. However, does any know how to place such information at the bottom of a graph?

Its seems like it should be easy to do but I just can't find anything online regarding how to do it. Is it even possible using R?

Any help would be gratefully appreciated!


Solution

  • Here is one way. For some dummy data

    set.seed(2)
    dat <- rnorm(100, mean = 3, sd = 3)
    

    compute the summary

    sdat <- summary(dat)
    

    We can then paste together the names of the summary statistics and their values using paste(), and collapse this to a single string

    summStr <- paste(names(sdat), format(sdat, digits = 2), collapse = "; ")
    

    Note that I format the values of the statistics to have just two significant digits using format(). This can be added to the plot say as a subtitle use the title() function

    op <- par(mar = c(7,4,4,2) + 0.1)
    hist(dat)
    title(sub = summStr, line = 5.5)
    par(op)
    

    I push the subtitle down the plot a little bit via argument line.

    text added to a plot as a subtitle