Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中同时绘制两个直方图?_R_Plot_Histogram - Fatal编程技术网

如何在R中同时绘制两个直方图?

如何在R中同时绘制两个直方图?,r,plot,histogram,R,Plot,Histogram,我使用的是R,我有两个数据帧:胡萝卜和黄瓜。每个数据帧都有一个数字列,列出所有测量的胡萝卜(总计:100k胡萝卜)和黄瓜(总计:50k黄瓜)的长度 我希望在同一个图上绘制两个直方图——胡萝卜长度和黄瓜长度。它们重叠,所以我想我也需要一些透明度。我还需要使用相对频率而不是绝对数字,因为每个组中的实例数是不同的 这样做很好,但我不知道如何从我的两个表中创建它: 您链接到的图像用于密度曲线,而不是直方图 如果您一直在阅读ggplot,那么可能您唯一缺少的就是将两个数据帧合并为一个长数据帧 那么,让我们

我使用的是R,我有两个数据帧:胡萝卜和黄瓜。每个数据帧都有一个数字列,列出所有测量的胡萝卜(总计:100k胡萝卜)和黄瓜(总计:50k黄瓜)的长度

我希望在同一个图上绘制两个直方图——胡萝卜长度和黄瓜长度。它们重叠,所以我想我也需要一些透明度。我还需要使用相对频率而不是绝对数字,因为每个组中的实例数是不同的

这样做很好,但我不知道如何从我的两个表中创建它:


您链接到的图像用于密度曲线,而不是直方图

如果您一直在阅读ggplot,那么可能您唯一缺少的就是将两个数据帧合并为一个长数据帧

那么,让我们从你拥有的东西开始,两组独立的数据,并将它们组合起来

carrots <- data.frame(length = rnorm(100000, 6, 2))
cukes <- data.frame(length = rnorm(50000, 7, 2.5))

# Now, combine your two dataframes into one.  
# First make a new column in each that will be 
# a variable to identify where they came from later.
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'

# and combine into your new data frame vegLengths
vegLengths <- rbind(carrots, cukes)

现在,如果你真的想要柱状图,下面的方法就行了。请注意,您必须更改默认“stack”参数的位置。如果你不知道你的数据应该是什么样子,你可能会错过这一点。阿尔法越高,效果越好。还要注意,我制作了密度直方图。很容易删除
y=…density..
以恢复计数

ggplot(vegLengths, aes(length, fill = veg)) + 
   geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')

以下是一个如何在“经典”R图形中实现的示例:

## generate some random data
carrotLengths <- rnorm(1000,15,5)
cucumberLengths <- rnorm(200,20,7)
## calculate the histograms - don't plot yet
histCarrot <- hist(carrotLengths,plot = FALSE)
histCucumber <- hist(cucumberLengths,plot = FALSE)
## calculate the range of the graph
xlim <- range(histCucumber$breaks,histCarrot$breaks)
ylim <- range(0,histCucumber$density,
              histCarrot$density)
## plot the first graph
plot(histCarrot,xlim = xlim, ylim = ylim,
     col = rgb(1,0,0,0.4),xlab = 'Lengths',
     freq = FALSE, ## relative, not absolute frequency
     main = 'Distribution of carrots and cucumbers')
## plot the second graph on top of this
opar <- par(new = FALSE)
plot(histCucumber,xlim = xlim, ylim = ylim,
     xaxt = 'n', yaxt = 'n', ## don't add axes
     col = rgb(0,0,1,0.4), add = TRUE,
     freq = FALSE) ## relative, not absolute frequency
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
       fill = rgb(1:0,0,0:1,0.4), bty = 'n',
       border = NA)
par(opar)
##生成一些随机数据

这是一个类似ggplot2的版本,我只在R基中给出了这个版本。我从@nullglob复制了一些

生成数据

carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)

carrots这是我写的一个函数

结果如下所示:

这里有一个更简单的解决方案,使用基本图形和alpha混合(不适用于所有图形设备):

set.seed(42)
p1可能对您有用。下图是

library(plotly)
#添加用户名和密钥

p@Dirk Eddelbuettel:基本思想很好,但所示代码可以改进。[解释需要很长时间,因此需要单独回答,而不是评论。]

默认情况下,
hist()
函数绘制绘图,因此需要添加
plot=FALSE
选项。此外,通过
绘图(0,0,type=“n”,…)
调用建立绘图区域更为清晰,在该调用中,您可以添加轴标签、绘图标题等。最后,我想提到的是,还可以使用阴影来区分两个直方图。代码如下:

set.seed(42)
p1 <- hist(rnorm(500,4),plot=FALSE)
p2 <- hist(rnorm(500,6),plot=FALSE)
plot(0,0,type="n",xlim=c(0,10),ylim=c(0,100),xlab="x",ylab="freq",main="Two histograms")
plot(p1,col="green",density=10,angle=135,add=TRUE)
plot(p2,col="blue",density=10,angle=45,add=TRUE)
set.seed(42)

p1已经有了漂亮的答案,但我想加上这个。我觉得不错。 (从@Dirk复制随机数)<代码>库(比例)
是必需的`

set.seed(42)
hist(rnorm(500,4),xlim=c(0,10),col='skyblue',border=F)
hist(rnorm(500,6),add=T,col=scales::alpha('red',.5),border=F)
结果是

更新:这个重叠函数对某些人也可能有用

hist0 <- function(...,col='skyblue',border=T) hist(...,col=col,border=border) 
结果

par(mar=c(3, 4, 3, 2) + 0.1) 
set.seed(100) 
hist2(rnorm(10000,2),rnorm(10000,3),breaks = 50)


有这么多好的答案,但由于我刚刚编写了一个函数(
plotMultipleHistograms()
in package)来实现这一点,我想我应该添加另一个答案

此函数的优点是,它自动设置适当的X轴和Y轴限制,并定义一组通用的箱子,用于所有分布

以下是如何使用它:

# Install the plotteR package
install.packages("devtools")
devtools::install_github("JosephCrispell/basicPlotteR")
library(basicPlotteR)

# Set the seed
set.seed(254534)

# Create random samples from a normal distribution
distributions <- list(rnorm(500, mean=5, sd=0.5), 
                      rnorm(500, mean=8, sd=5), 
                      rnorm(500, mean=20, sd=2))

# Plot overlapping histograms
plotMultipleHistograms(distributions, nBins=20, 
                       colours=c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.5), rgb(0,1,0, 0.5)), 
                       las=1, main="Samples from normal distribution", xlab="Value")
#安装绘图仪软件包
安装包(“devtools”)
devtools::安装github(“JosephCrispell/basicPlotteR”)
图书馆(BasicLotter)
#播种
种子集(254534)
#从正态分布创建随机样本

顺便问一下,你打算使用哪种软件?对于开源,我推荐[gnuplot]。在它的文档中,我相信你会找到一些技术和示例脚本来做你想做的事情。我正在使用标签所建议的R(编辑帖子以澄清这一点)有人在这个线程中发布了一些代码片段来做这件事:如果你想继续使用直方图,请使用
ggplot(veglength,aes(length,fill=veg))+geom_bar(pos=“dodge”)
。这将使交错直方图,如在MATLAB。Thx的答案!‘position=“identity”’部分实际上很重要,否则钢筋会堆叠起来,这在与默认情况下似乎是“identity”的密度相结合时会产生误导,即重叠而不是堆叠。非常好。这也让我想起了有人提出这个问题,因为这个答案是唯一一个(除了
ggplot
中的答案)可以直接解释两个直方图是否有实质性不同的样本大小。我喜欢这个方法,请注意,可以通过使用seq()定义它们来同步中断。例如:
breaks=seq(min(data$some\u property)、max(data$some\u property)、by=(max\u prop-min\u prop)/20)
+1谢谢大家,这可以转换成更平滑的gistogram(like)吗?为什么要分离出
plot
命令?您可以将所有这些选项放入
hist
命令中,只需在两行中添加两个即可。@John您会怎么做?如我所说,将
plot
命令中的选项直接放入hist命令中。张贴代码不是注释的目的。所有图形设备(例如,
postscript
)上都提供+1选项,因为这是一个非常简单的选项,可以在
postscript
设备上使用。
library(plotly)
#add username and key
p <- plotly(username="Username", key="API_KEY")
#generate data
x0 = rnorm(500)
x1 = rnorm(500)+1
#arrange your graph
data0 = list(x=x0,
         name = "Carrots",
         type='histogramx',
         opacity = 0.8)

data1 = list(x=x1,
         name = "Cukes",
         type='histogramx',
         opacity = 0.8)
#specify type as 'overlay'
layout <- list(barmode='overlay',
               plot_bgcolor = 'rgba(249,249,251,.85)')  
#format response, and use 'browseURL' to open graph tab in your browser.
response = p$plotly(data0, data1, kwargs=list(layout=layout))

url = response$url
filename = response$filename

browseURL(response$url)
set.seed(42)
p1 <- hist(rnorm(500,4),plot=FALSE)
p2 <- hist(rnorm(500,6),plot=FALSE)
plot(0,0,type="n",xlim=c(0,10),ylim=c(0,100),xlab="x",ylab="freq",main="Two histograms")
plot(p1,col="green",density=10,angle=135,add=TRUE)
plot(p2,col="blue",density=10,angle=45,add=TRUE)
set.seed(42)
hist(rnorm(500,4),xlim=c(0,10),col='skyblue',border=F)
hist(rnorm(500,6),add=T,col=scales::alpha('red',.5),border=F)
hist0 <- function(...,col='skyblue',border=T) hist(...,col=col,border=border) 
hist2 <- function(var1, var2,name1='',name2='',
              breaks = min(max(length(var1), length(var2)),20), 
              main0 = "", alpha0 = 0.5,grey=0,border=F,...) {    

library(scales)
  colh <- c(rgb(0, 1, 0, alpha0), rgb(1, 0, 0, alpha0))
  if(grey) colh <- c(alpha(grey(0.1,alpha0)), alpha(grey(0.9,alpha0)))

  max0 = max(var1, var2)
  min0 = min(var1, var2)

  den1_max <- hist(var1, breaks = breaks, plot = F)$density %>% max
  den2_max <- hist(var2, breaks = breaks, plot = F)$density %>% max
  den_max <- max(den2_max, den1_max)*1.2
  var1 %>% hist0(xlim = c(min0 , max0) , breaks = breaks,
                 freq = F, col = colh[1], ylim = c(0, den_max), main = main0,border=border,...)
  var2 %>% hist0(xlim = c(min0 , max0),  breaks = breaks,
                 freq = F, col = colh[2], ylim = c(0, den_max), add = T,border=border,...)
  legend(min0,den_max, legend = c(
    ifelse(nchar(name1)==0,substitute(var1) %>% deparse,name1),
    ifelse(nchar(name2)==0,substitute(var2) %>% deparse,name2),
    "Overlap"), fill = c('white','white', colh[1]), bty = "n", cex=1,ncol=3)

  legend(min0,den_max, legend = c(
    ifelse(nchar(name1)==0,substitute(var1) %>% deparse,name1),
    ifelse(nchar(name2)==0,substitute(var2) %>% deparse,name2),
    "Overlap"), fill = c(colh, colh[2]), bty = "n", cex=1,ncol=3) }
par(mar=c(3, 4, 3, 2) + 0.1) 
set.seed(100) 
hist2(rnorm(10000,2),rnorm(10000,3),breaks = 50)
# Install the plotteR package
install.packages("devtools")
devtools::install_github("JosephCrispell/basicPlotteR")
library(basicPlotteR)

# Set the seed
set.seed(254534)

# Create random samples from a normal distribution
distributions <- list(rnorm(500, mean=5, sd=0.5), 
                      rnorm(500, mean=8, sd=5), 
                      rnorm(500, mean=20, sd=2))

# Plot overlapping histograms
plotMultipleHistograms(distributions, nBins=20, 
                       colours=c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.5), rgb(0,1,0, 0.5)), 
                       las=1, main="Samples from normal distribution", xlab="Value")