我需要在矩阵行的同一图表中绘制对齐的直方图。在下面的例子中,我需要绘制5个堆叠的直方图。但是,hist命令绘制整个矩阵的一个直方图。我可以使用任何解决方法吗?
提前致谢。
的Arturo
Execute
答案 0 :(得分:1)
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)
答案 1 :(得分:-1)
这是我正在使用的方法,以便在同一图表中生成两个直方图。
考虑使用数据集,其中列x是连续var,列y是因子变量;每个级别将产生一个直方图。请在下面找到使用ggplot2的代码示例:
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
我希望这会有所帮助。
干杯! ķ。