Filling bars in barplot with textiles rather than color in R

前端 未结 2 1793
花落未央
花落未央 2020-12-29 11:22

I am trying to fill bars in a barplot using different textiles rather than color.

I know how to fill the bars with different patterns of lines like this:

<         


        
相关标签:
2条回答
  • 2020-12-29 11:27

    plotrix package provides rectFill and barp functions, which allow to fill the bars with custom shapes.

    barp produces barplots and calls rectFill to fill them with symbols. The symbols can be specified using default pch parameters (reference chart), or via custom string, see the examples below.

    # install the package
    install.packages('plotrix')
    
    # examples with varying pch parameters
    require(plotrix)
    a <- 1:4
    barp(t(a), pch=t(1:4))
    barp(t(a), pch=t(c("*","$","~","@")))
    

    Unfortunately barp is not very flexible:

    1. The data has to be supplied in a matrix format to specify varying symbols. The columns of the matrix should correspond with the sequence of pch parameters. Hence the need for t() in the current examples.

    2. Once pch is specified, the plot becomes black and white. rectFill function allows to control the colour of the symbols via pch.col, but the barp doesn't allow this option. To address this, I added the ellipsis (...) to the barp source code to be able to pass further arguments to the rectFill function. The modified code (barp2) is available here.

    Example using modified code:

    # load the barp2 function
    require(devtools)
    source_gist("https://gist.github.com/tleja/8592929")
    
    # run the barp2 function
    require(plotrix)
    a <- 1:4
    barp2(t(a), pch=t(1:4), pch.col=1:4)
    

    enter image description here


    EDIT: It appears that the most recent version of the package may have a bug, since some users are having trouble reproducing the plots. If that happens, please try installing the earlier version of plotrix using the code below:

    require(devtools)
    install_url("http://cran.r-project.org/src/contrib/Archive/plotrix/plotrix_3.5-2.tar.gz") 
    
    0 讨论(0)
  • 2020-12-29 11:39

    I'm sure something like below can be adapted:

    aaa <- c(1,2,3,4)
    bp <- barplot(aaa,col="white")
    
    fillbars <- function(height,bp,bg,size,spacing) {
      coords <- data.frame(bp-0.5,bp+0.5,0,height)
      invisible(
        apply(
          coords,
          1,
          function(d) {
            do.call(clip,unname(as.list(d)))
            x <- seq(d[1],d[2],by=spacing)
            y <- seq(d[3],d[4],by=spacing)
            xy <- expand.grid(x,y)
            symbols(
              xy,
              circles=rep(size,nrow(xy)),
              inches=FALSE,
              bg=bg,
              add=TRUE
            )
          }
        )
      )
    }
    
    fillbars(height=aaa,bp=bp,bg="red",size=0.06,spacing=0.3)
    

    Result:

    enter image description here

    0 讨论(0)
提交回复
热议问题