如何在图表上写均值,最小值,最大值,中位数,P值和安德森亲爱的测试结果

时间:2018-10-28 08:26:07

标签: r ggplot2

我作图时遇到了问题。

enter image description here

我想在图的右侧添加均值,最小值,最大值,中位数,P值和安德森亲爱的测试结果。 但我不知道如何发布每个类似“均值= 70.0”的结果 请回答我如何编写正确的代码。

library(xlsx)
library(nortest)
library(ggplot2)
data1=read.xlsx("data_example.xlsx",1)
study1=data1$Normal
y=dnorm(study1,mean(study1),sd(study1))
norm= data.frame(study1,y)
min=min(study1)
max=max(study1)
mean=mean(study1)
median=median(study1)
sd=sd(study1)
ggplot(norm, aes(x=study1)) + geom_histogram(aes(x=study1,y=..density..), 
binwidth=2, color='black', fill='blue', alpha='.2') +
labs(title = 'Normal에 대한 요약보고서') + 
geom_density(aes(x=study1,y=..density..)) +
annotate("text", label = min, x = 100, y = .04, color = "black") + 
annotate("text", label = max, x = 100, y = .035, color = "black") +
annotate("text", label = mean, x = 100, y = .03, color = "black") + 
annotate("text", label = median, x = 100, y = .025, color = "black")

1 个答案:

答案 0 :(得分:2)

加载库:

library(dplyr)
library(ggplot2)

生成正态分布的数据:

set.seed(11235813)
x <- rnorm(2000, mean = 70.0, sd = 11.5)

计算参数(minmax,...),然后将结果转换为字符向量:

xpars <- sapply(c("min", "max", "mean", "median", "sd"), do.call, list(x = x)) %>%
  round(., 2) %>%
  paste(names(.), ., sep = " = ") %>%
  paste(., collapse = "\n")

x设为data.frame,然后绘制数据(我只是稍微修改了您的代码):

data.frame(x = x) %>%
      ggplot(aes(x = x)) +
      geom_histogram(aes(y = ..density..), binwidth = 2, 
                     colour = "black", fill = "blue", alpha = .2) +
      geom_density(aes(y = ..density..), colour = "red", lty = 2) +
      annotate("text", x = 0.9*max(x), y = .9*max(density(x)$y), label = xpars, hjust = 0) +
      ggtitle("Normal에 대한 요약보고서") +
      theme_classic()

histogram_with_summary