如何使用 ggplot2 在直方图中添加汇总统计信息?

Bap*_*Das 7 r histogram ggplot2 dplyr

我想在使用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)
Run Code Online (Sandbox Code Playgroud)

它给了我以下情节 在此处输入图片说明

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

Stu*_*olf 6

您需要拆分 data.frame:

\n\n
p1+geom_table_npc(data=summ,label =split(summ,summ$variable),\nnpcx = 0.00, npcy = 1, hjust = 0, vjust = 1,size=2)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在此输入图像描述

\n\n

或嵌套您拥有的汇总表:

\n\n
summ <- summ %>% nest(data=-c(variable))\n\n# A tibble: 4 x 2\n  variable               data\n  <fct>        <list<df[,9]>>\n1 Sepal.Length        [1 \xc3\x97 9]\n2 Sepal.Width         [1 \xc3\x97 9]\n3 Petal.Length        [1 \xc3\x97 9]\n4 Petal.Width         [1 \xc3\x97 9]\n\np1+geom_table_npc(data = summ,label =summ$data,\n,npcx = 0.00, npcy = 1, hjust = 0, vjust = 1)\n
Run Code Online (Sandbox Code Playgroud)\n

  • summ %&gt;% mutate_if(is.numeric,round,digits=2) ?或者类似的事情..你必须在餐桌前做 (2认同)