[英]Plotting aligned histograms in the same graph
我需要在矩陣行的同一圖表中繪制對齊的直方圖。 在下面的例子中,我需要繪制5個堆疊的直方圖。 但是,hist命令繪制整個矩陣的一個直方圖。 我可以使用任何解決方法嗎?
提前致謝。
阿圖羅
x <- 10; y <- 10; g <- 5
dat <- matrix(rnorm((x + y) * g), ncol = x + y)
hist (dat)
ggplot
很容易做到(它需要一個長格式數據)。
library(tidyr); library(dplyr); library(ggplot2)
df <- dat %>% t() %>% as.data.frame() %>% gather(row) # chage data into a long format
Breaks <- hist(dat, plot=F)$breaks # get (or decide) breaks
ggplot(df, aes(x = value, fill = row)) + geom_histogram(position = "stack", breaks = Breaks)
[EDITED]
這是你想要的嗎 ?
## original
ggplot(df, aes(x = value)) +
geom_histogram(breaks = Breaks) +
facet_wrap(~ row) # make histogram par group.
## modified
ggplot(df, aes(x = value, fill = row)) + # change fill colour
geom_histogram(breaks = Breaks) +
facet_wrap(~ row, ncol = 1) + # bring graphs into line
# facet_wrap( ~ row, ncol = 1, scales = "free_y") # if you don't want fixed scale
theme(strip.background = element_blank(), strip.text.x = element_blank()) # delete labels
[EDITED2:base_plot方法]
基礎圖節省時間。
## example data
x <- 1500; y <- 1500; g <- 30
set.seed(1); dat <- matrix(rnorm((x + y) * g), ncol = x + y)
## decide breaks
Breaks <- seq(-4.5, 4.5, 0.5)
## change par() to draw multiple graphs
par.old <- par(mar = c(0.1, 4.0, 0.1, 0.5), oma = c(4, 0, 0, 0), mfrow = c(nrow(dat), 1))
for(i in 1:nrow(dat)) {
hist(dat[,i], breaks = Breaks, xaxt = "n", xlab = "", main = "")
# grid(NULL)
}
par(new=T)
hist(dat[,nrow(dat)], breaks = Breaks, main = "", yaxt = "n",
xlab = "x", ylab = "", border = NA) # add x-axis
par(par.old)
這是我使用的方法,以便在同一圖表中生成兩個直方圖。
考慮使用數據集,其中列x是連續var,列y是因子變量; 每個級別將產生一個直方圖。 請在下面找到使用ggplot2的代碼示例:
OverlayedHist <- function(mData ,
featureVar ,
grouper ,
mbinwidth ,
mTitle ,
mxlab ,
mylab ,
mlegendTitle
){
# function name: OverlayedHist
# purpose: To produce overlayed histograms against a grouping variable
# Input:
# mData: dataset object in data.table format
# featureVar: name of continuous variable to produce histogram
# grouper: the grouping variable to produce the histogram
# mbinwidth: binwidth (see ggplot2 parameters)
# mTitle: Character to define title
# mxlab: Character to define xlab name
# mylab: Character to define ylab name
# mlegendTitle: Character to define legend title
library(data.table)
library(ggplot2)
library(plotly)
p <- ggplot(allDat, aes(eval(parse(text = featureVar)), fill = eval(parse(text = grouper)))) +
geom_histogram(alpha = 0.7, position = 'identity', binwidth = mbinwidth) +
scale_fill_manual(values=c("#377EB8","#E41A1C")) +
ggtitle(mTitle) +
xlab(mxlab) + ylab(mylab) +
guides(fill=guide_legend(title=mlegendTitle)) + theme(plot.title = element_text(size=10))
return(ggplotly(p))
}
我希望這有幫助。
干杯! K.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.