11

I want to add summary statistics in histogram plot made using ggplot2. I am using the following code

#Loading the required packages
library(dplyr)
library(ggplot2)
library(reshape2)
library(moments)
library(ggpmisc)

#Loading the data
df <- iris
df.m <- melt(df, id="Species")

#Calculating the summary statistics
summ <- df.m %>% 
  group_by(variable) %>% 
  summarize(min = min(value), max = max(value), 
            mean = mean(value), q1= quantile(value, probs = 0.25), 
            median = median(value), q3= quantile(value, probs = 0.75),
            sd = sd(value), skewness=skewness(value), kurtosis=kurtosis(value))

#Histogram plotting
p1 <- ggplot(df.m) + geom_histogram(aes(x = value), fill = "grey", color = "black") + 
  facet_wrap(~variable, scales="free", ncol = 2)+ theme_bw()

p1+geom_table_npc(data = summ, label = list(summ),npcx = 0.00, npcy = 1, hjust = 0, vjust = 1)

It is giving me the following plot enter image description here

Every facet is having summary statistics of all the variables. I want it should show the summary statistics of the faceted variable only. How to do it?

1 Answer 1

6

You need to split your data.frame:

p1+geom_table_npc(data=summ,label =split(summ,summ$variable),
npcx = 0.00, npcy = 1, hjust = 0, vjust = 1,size=2)

enter image description here

or nest the summary table you have:

summ <- summ %>% nest(data=-c(variable))

# A tibble: 4 x 2
  variable               data
  <fct>        <list<df[,9]>>
1 Sepal.Length        [1 × 9]
2 Sepal.Width         [1 × 9]
3 Petal.Length        [1 × 9]
4 Petal.Width         [1 × 9]

p1+geom_table_npc(data = summ,label =summ$data,
,npcx = 0.00, npcy = 1, hjust = 0, vjust = 1)
Sign up to request clarification or add additional context in comments.

2 Comments

How can we round the values to two decimal places?
summ %>% mutate_if(is.numeric,round,digits=2) ? or something like that.. you have to do it before the table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.