【问题标题】:How to add summary statistics in histogram plot using ggplot2?如何使用 ggplot2 在直方图中添加汇总统计?
【发布时间】:2020-07-14 11:50:33
【问题描述】:

我想在使用ggplot2 制作的直方图中添加汇总统计信息。我正在使用以下代码

#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)

它给了我以下情节

每个方面都有所有变量的汇总统计信息。我希望它只显示多面变量的汇总统计信息。怎么做?

【问题讨论】:

    标签: r ggplot2 dplyr histogram


    【解决方案1】:

    你需要拆分你的data.frame:

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

    或嵌套您拥有的汇总表:

    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)
    

    【讨论】:

    • 我们如何将值四舍五入到小数点后两位?
    • summ %>% mutate_if(is.numeric,round,digits=2) ?或类似的东西......你必须在桌子之前做它
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 2019-02-18
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多