【r<-标准绘图 | 直方图和密度图】

作者: 王诗翔 | 来源:发表于2018-10-30 22:53 被阅读1次

    问题

    你想要绘制一个直方图或密度图。

    方案

    一些样例数据:两个分别包含200个数据点的向量:

    set.seed(1234)
    rating  <- rnorm(200)
    head(rating)
    #> [1] -1.2070657  0.2774292  1.0844412 -2.3456977  0.4291247  0.5060559
    
    rating2 <- rnorm(200, mean=.8)
    head(rating2)
    #> [1] 1.2852268 1.4967688 0.9855139 1.5007335 1.1116810 1.5604624
    

    当可视化含多个组别的数据时,一些绘图方法通常需要一个数据框:一列给分组变量,一列给测量值。

    # 创建一列用于显示数据的组别
    cond <- factor( rep(c("A","B"), each=200) )
    
    data <- data.frame(cond, rating = c(rating,rating2))
    head(data)
    #>   cond     rating
    #> 1    A -1.2070657
    #> 2    A  0.2774292
    #> 3    A  1.0844412
    #> 4    A -2.3456977
    #> 5    A  0.4291247
    #> 6    A  0.5060559
    # 直方图
    hist(rating)
    
    # 使用8个箱子(这仅仅是近似 - 它会把边界放在一个比较好的近似值上)
    # 让箱子呈现淡蓝色 #CCCCFF
    # 相比于计数,这里让面积为1,即显示比例(freq=FALSE)
    hist(rating, breaks=8, col="#CCCCFF", freq=FALSE)
    
    # 每0.6一个刻度
    boundaries <- seq(-3, 3.6, by=.6)
    boundaries
    #>  [1] -3.0 -2.4 -1.8 -1.2 -0.6  0.0  0.6  1.2  1.8  2.4  3.0  3.6
    
    hist(rating, breaks=boundaries)
    
    
    # 核密度图
    plot(density(rating))
    
    plot of chunk unnamed-chunk-4 plot of chunk unnamed-chunk-4 plot of chunk unnamed-chunk-4 plot of chunk unnamed-chunk-4

    多个组别的核密度图

    代码来自: http://onertipaday.blogspot.com/2007/09/plotting-two-or-more-overlapping.html

    plot.multi.dens <- function(s)
    {
        junk.x = NULL
        junk.y = NULL
        for(i in 1:length(s)) {
            junk.x = c(junk.x, density(s[[i]])$x)
            junk.y = c(junk.y, density(s[[i]])$y)
        }
        xr <- range(junk.x)
        yr <- range(junk.y)
        plot(density(s[[1]]), xlim = xr, ylim = yr, main = "")
        for(i in 1:length(s)) {
            lines(density(s[[i]]), xlim = xr, ylim = yr, col = i)
        }
    }
    
    # 下面函数的输入必须是一个数值列表
    plot.multi.dens( list(rating, rating2))
    
    plot of chunk unnamed-chunk-5

    sm 包也引入了一种绘制多个密度图的方式,输入数据必须是数据框。

    library(sm)
    sm.density.compare(data$rating, data$cond)
    # 添加一个图例 (颜色编号从2往上升)
    legend("topright", levels(data$cond), fill=2+(0:nlevels(data$cond)))
    
    plot of chunk unnamed-chunk-6

    原文链接:http://www.cookbook-r.com/Graphs/Histogram_and_density_plot/

    相关文章

      网友评论

        本文标题:【r<-标准绘图 | 直方图和密度图】

        本文链接:https://www.haomeiwen.com/subject/hgontqtx.html