Rotate histogram in R or overlay a density in a barplot

后端 未结 5 878
一个人的身影
一个人的身影 2021-01-31 12:01

I would like to rotate a histogram in R, plotted by hist(). The question is not new, and in several forums I have found that it is not possible. However, all these answers date

5条回答
  •  耶瑟儿~
    2021-01-31 12:46

    It may be helpful to know that the hist() function invisibly returns all the information that you need to reproduce what it does using simpler plotting functions, like rect().

        vals <- rnorm(10)
        A <- hist(vals)
        A
        $breaks
        [1] -1.5 -1.0 -0.5  0.0  0.5  1.0  1.5
    
        $counts
        [1] 1 3 3 1 1 1
    
        $intensities
        [1] 0.2 0.6 0.6 0.2 0.2 0.2
    
        $density
        [1] 0.2 0.6 0.6 0.2 0.2 0.2
    
        $mids
        [1] -1.25 -0.75 -0.25  0.25  0.75  1.25
    
        $xname
        [1] "vals"
    
        $equidist
        [1] TRUE
    
        attr(,"class")
        [1] "histogram"
    

    You can create the same histogram manually like this:

        plot(NULL, type = "n", ylim = c(0,max(A$counts)), xlim = c(range(A$breaks)))
        rect(A$breaks[1:(length(A$breaks) - 1)], 0, A$breaks[2:length(A$breaks)], A$counts)
    

    With those parts, you can flip the axes however you like:

        plot(NULL, type = "n", xlim = c(0, max(A$counts)), ylim = c(range(A$breaks)))
        rect(0, A$breaks[1:(length(A$breaks) - 1)], A$counts, A$breaks[2:length(A$breaks)])
    

    For similar do-it-yourselfing with density(), see: Axis-labeling in R histogram and density plots; multiple overlays of density plots

提交回复
热议问题