Reputation: 13
I had a problem when I made a plot.
I want to add result of mean, min, max, median, P-value and anderson-darling test on the right side of the plot. But I don't know how post each result like 'mean = 70.0' please answer me how can I write proper code.
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")
Upvotes: 1
Views: 401
Reputation: 4520
Load the libraries:
library(dplyr)
library(ggplot2)
Generate a normally distributed data:
set.seed(11235813)
x <- rnorm(2000, mean = 70.0, sd = 11.5)
Calculate the parameters (min
, max
, ... ), and convert the results to the character vector:
xpars <- sapply(c("min", "max", "mean", "median", "sd"), do.call, list(x = x)) %>%
round(., 2) %>%
paste(names(.), ., sep = " = ") %>%
paste(., collapse = "\n")
Make x
a data.frame
, and plot the data (I just slightly modified your code):
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 = .9 * max(x),
y = .9 * max(density(x)$y),
label = xpars,
hjust = 0
) +
ggtitle("Normal에 대한 요약보고서") +
theme_classic()
Upvotes: 2