データ
#<font size="1"> This is my text number1</font>
set.seed(123)
dat <- data.frame(x = rnorm(500, 90, 10),
y = rnorm(500, 60, 10),
z = rnorm(500, 30, 10))
dat
|
x
|
y
|
z
|
|
84.39524
|
53.98107
|
20.042013
|
|
87.69823
|
50.06301
|
19.600450
|
|
105.58708
|
70.26785
|
29.820198
|
|
90.70508
|
67.51061
|
28.678249
|
|
91.29288
|
44.90833
|
4.506572
|
|
107.15065
|
59.04853
|
40.405735
|
hist
# function
mhist <- function(x, cols, brk=NULL, xlb="", mt=""){
# x軸,y軸範囲を指定する関数
wrange <- function(v){
# min or max value
mn <- range(v)[1]
mx <- range(v)[2]
# round function
wr <- function(x){
if (x < 0 ) {
n = 10^floor(log10(abs(x)))
res <- ceiling(abs(x)/n) * n * -1
} else if (x > 0 ) {
n = 10^floor(log10(x))
res <- ceiling(x/n) * n
} else if (x == 0) {
res <- 0
}
return(res)
}
# return
wmx <- wr(mx)
if (!mn <= 0) { wmn <- 0 } else { wmn <- wr(mn) }
return(c(wmn, wmx))
}
# x軸範囲, y軸範囲, # breaks
if(is.null(brk)){
xlm <- range(unlist(x))
hv <- lapply(x, function(v) hist(v, plot = FALSE))
cnts <- sapply(hv, function(x)x$counts)
ylm <- wrange(range(unlist(cnts)))
dst <- min(sapply(hv, function(x)x$breaks[2]-x$breaks[1]))
brks <- sapply(hv, function(x)x$breaks)
brk <- seq(min(unlist(brks)), max(unlist(brks)), dst)
} else {
xlm <- range(unlist(x))
hv <- lapply(x, function(v) hist(v, breaks = brk, plot = FALSE))
cnts <- sapply(hv, function(x)x$counts)
ylm <- wrange(range(unlist(cnts)))
}
# hist
for(i in seq_along(x)) {
if(i==1){
hist(x[[i]], ylim = ylm, xlim = xlm, col = cols[i], breaks = brk, main = mt, xlab=xlb)
} else if(i>1){
hist(x[[i]], ylim = ylm, xlim = xlm, col = cols[i], breaks = brk, add=TRUE)
}
}
legend('topright', legend = names(x), fill=cols, border = F, box.lwd = F)
return(hv)
}
# plot
par(mfcol=c(1,2))
cols <- adjustcolor(c("#999999", "#E69F00", "#56B4E9"), alpha.f = 0.5)
res <- mhist(x = dat, cols = cols)
res <- mhist(x = dat, cols = cols, brk = 30)

geom_histogram
# function
ggmhist <- function(x, cols=seq_along(x), binwd=20){
ggdat <- tidyr::gather(x, "k", "v")
ggplot2::ggplot(ggdat, ggplot2::aes(x = v, fill = k), colour = k) +
ggplot2::geom_histogram(binwidth = binwd, position = "identity") +
ggplot2::scale_fill_manual(values = cols)
}
# plot
cols <- adjustcolor(RColorBrewer::brewer.pal(3, "Set1"), 0.5)
ggmhist(dat, cols, binwd = 5)
