UseR10085
UseR10085

Reputation: 8136

How to add summary statistics in histogram plot using ggplot2?

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?

Upvotes: 10

Views: 4516

Answers (1)

StupidWolf
StupidWolf

Reputation: 46898

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)

Upvotes: 6

Related Questions