【问题标题】:R Create a histogram with distribution curveR创建带有分布曲线的直方图
【发布时间】:2014-01-20 00:21:21
【问题描述】:

我想在同一个窗口中使用 txt 文件中的“data1”和“data2”制作两个不同的直方图和分布曲线。我可以创建一个直方图,其中包含“data1”和“data2”列中的数据组合但不分开。如何分离我的数据?谢谢。

data1  data2
155      130
195      10
21       26
15       210
190      15
2        205
182      50
115      55
170      1
17       56

Data = as.matrix( read.table( "c:\\Data.txt",header=TRUE ) )
attach( Data )

par( mfrow=c(1,2) ) #c(rows,columns)

hist(Data ,plot=TRUE, col=c("red","blue"),
     main = "Histogram of Data1",
     xlab="X-Axis", ylab="Y-Axis", cex.lab= 1, col.lab="blue" )

#Curve is not working even if data is combined
curve(dnorm(x, mean=mean(Data), sd=sd(Data)), add=TRUE, col="blue", lwd=2)

【问题讨论】:

  • 它给出错误:Data$data1 中的错误:$ 运算符对原子向量 hist(Data$data1,plot=TRUE, col=c("red","blue"), main = 无效"数据1的直方图", xlab="X-Axis", ylab="Y-Axis", cex.lab= 1, col.lab="blue", prob=TRUE )

标签: r histogram


【解决方案1】:

或者试试这个:

Data <- structure(list(data1 = c(155, 195, 21, 15, 190, 2, 182, 115, 
                                 170, 17), data2 = c(130, 10, 26, 210, 15, 205, 50, 55, 1, 56)), .Names = c("data1", 
                                                                                                            "data2"), row.names = c(NA, -10L), class = "data.frame")
par( mfrow=c(1,2) ) 
invisible(lapply(1:ncol(Data), function(i){
  x <- Data[,i]
  h <- hist(x, col=c("red","blue"),
            main = paste0("Histogram of ", names(Data)[i]),
            xlab="X-Axis", ylab="Y-Axis", breaks=5,
            cex.lab= 1, col.lab="blue")
  xfit<-seq(min(x),ceiling(210/50)*50,length=40) 
  yfit<-dnorm(xfit,mean=mean(x),sd=sd(x)) 
  yfit <- yfit*diff(h$mids[1:2])*length(x) 
  lines(xfit, yfit, col="green", lwd=2)
}))

(source)

【讨论】:

  • 我想使用“read”命令从 txr 中获取值,而不是手动添加列的值。有一个命令可以将您从 txt 文件中读取的列分开?
  • 您可以使用read.table 读取逗号/制表符/...-分隔值。
【解决方案2】:

试试这个

par( mfrow=c(1,2) ) 
invisible(lapply(1:ncol(Data), function(i){
  x <- Data[,i]
  hist(x, col=c("red","blue"),
       main = paste0("Histogram of ", names(Data)[i]),
       xlab="X-Axis", ylab="Y-Axis", 
       cex.lab= 1, col.lab="blue",
       prob=TRUE)

  curve(dnorm(x, mean=mean(x), sd=sd(x)), 
        add=TRUE, col="blue", lwd=2)

}))

par( mfrow=c(1,1))

【讨论】:

    猜你喜欢
    • 2014-01-09
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2021-12-04
    • 2019-11-04
    相关资源
    最近更新 更多