R/ggplot2.customize.R

#' @include ggplot2.setAxis.R
NULL
#' Customize a graph generated by ggplot2 package (axis, title, background,
#' color, legend, ....)
#' @description Customize a graph generated by ggplot2 package
#' @param plot A plot object generated with ggplot2 or easyGgplot2 packages
#' (boxplot, densityplot, histogram, dotplot, ....)
#' @param \dots Any argument from the list of the arguments indicated below.
#' @details
#' \itemize{
#'\item{plot}{
#'  A plot object generated with ggplot2 or easyGgplot2 packages (boxplot, densityplot, histogram, dotplot, ....)
#'}
#'\item{\dots}{
#' Any argument from the list of the arguments indicated below.
#'}
#' \strong{Customize plot title}
#'\item{mainTitle}{ Title of the plot.}
#'\item{mainTitleFont}{ A vector of length 3 indicating respectively the size, the style and the color of main title. Possible values for font style are "plain", "italic", "bold", "bold.italic". Color can be specified as an hexadecimal code (e.g: "#FFCC00") or by the name (e.g : "red", "green"). Default value is: mainTitleFont=c(14, "bold", "black").}
#'
#'\strong{Customize x and y axis}
#'\item{xShowTitle, yShowTitle}{if TRUE, x axis and y axis titles will be shown. \strong{Default values are TRUE.}}
#'\item{xtitle, ytitle}{x and y axis labels.}
#'\item{xtitleFont, ytitleFont}{A vector of length 3 indicating respectively the size, the style and the color of x and y axis titles. \strong{Default values are c(14,"bold", "black").}}
#'\item{xlim, ylim}{Limit for the x and y axis. \strong{Default values are NULL}.}
#'\item{xScale, yScale}{x and y axis scales. Possible values are c("none", "log2", "log10"). Example: yScale="log2". \strong{Default values are "none".}}
#'\item{xShowTickLabel, yShowTickLabel}{if TRUE, x and y axis tick mark labels will be shown. \strong{Default values are TRUE.}}
#'\item{xTickLabelFont, yTickLabelFont}{A vector of length 3 indicating respectively the size, the style and the color of x and y axis tick label fonts. \strong{Default values are c(12, "bold", "black").}}
#'\item{xtickLabelRotation, ytickLabelRotation}{Rotation angle of x and y axis tick labels. \strong{Default values are 0.}}
#'\item{hideAxisTicks}{if TRUE, x and y axis ticks are removed. \strong{Default value is FALSE}.}
#'\item{axisLine}{A vector of length 3 indicating respectively the size, the line type and the color of axis lines.\strong{ Default value is c(0.5, "solid", "#E5E5E5").}}
#'
#'\strong{Customize plot background}
#'\item{removePanelBorder}{if TRUE, the top-right border of the plot are removed. \strong{Default value is FALSE.}}
#'\item{removePanelGrid}{if TRUE, panel grids are removed. \strong{Default value is FALSE.}}
#'\item{backgroundColor}{background color of plot panel. \strong{Default value is "gray".}}
#'\item{gridColor}{Color of plot panel grids. \strong{Default value is "white".}}
#'
#'\strong{Customize plot legend}
#'\item{showLegend}{if TRUE, plot legend will be shown. \strong{Default value is TRUE.}}
#'\item{legendPosition}{Position of legend box. \strong{Default value is "right"}. Possible values for legend position are "right", "left","top", "bottom". LegendPosition can be also a numeric vector c(x, y) indicating the coordinate of legend box. x and y values must be between 0 and 1. c(0,0) corresponds to the "bottom left" and  c(1,1) corresponds to the "top right" position.}
#'\item{legendBackground}{A vector of length 4 indicating boxFill, boxLineSize, boxLineType, boxLineColor. \strong{Default value is legendBackground=c("#FFFFFF", 0.5, "blank", "black" ).}}
#'\item{legendTextFont}{A vector of length 3 indicating respectively the size, the style and the color of legend text. \strong{Default value is c(10, "plain", "black")}. Possible values for font style are "plain", "italic", "bold", "bold.italic".}
#'\item{legendTitleFont}{A vector of length 3 indicating respectively the size, the style and the color of legend title. \strong{Default value is c(10, "plain", "black")}}
#'\item{legendItemOrder}{Character vector indicating the order of items in the legends. Example:  c("2", "1", "0.5")}
#'
#'\strong{Faceting : split a plot into a matrix of pannels}
#'\item{faceting}{if TRUE, the data are split up by one or two variables and graphs are displayed in different panels. In this case, you have to indicate the facetingVarNames. \strong{Default value is FALSE.}}
#'\item{facetingVarNames}{the names of the columns containing variables to use for faceting. \strong{Default value is NULL.}}
#'\item{facetingDirection}{possibles values are "vertical" and "horizontal". Default value is vertical. \strong{Default value is "vertical".}}
#'\item{facetingScales}{ By default, all the panels have the same scale (`facetingScales="fixed"`). They can be made independent, by setting scales to "free", "free_x", or "free_y". \strong{Default value is "fixed".}}
#'\item{facetingFont}{Change facet label apperance. A vector of length 3 indicating respectively the size, the font style and the color of the text. \strong{Default value is facetingFont=c(size=12, font="plain", color="black").}}
#'\item{facetingRect}{Modify the apperance of the rectangle around the facet label.\strong{Default value is list(background=NULL, lineType=NULL, lineColor=NULL, lineSize=NULL).} }
#'\item{facetingTextAngles}{Modify the facet label text orientation. It indicates the angles of the x and y texts (in [0, 360]). \strong{Default value is c(NULL, NULL).} }
#'
#'\strong{Others}
#'\item{orientation}{Change the orientation of the plot. Possible values are c("standard", "horizontal", "yAxisReversed"). \strong{Default value is "standard".}}
#'
#'}
#' @return a ggplot
#' @author Alboukadel Kassambara <alboukadel.kassambara@@gmail.com>
#' @seealso \code{\link{ggplot2.dotplot}, \link{ggplot2.violinplot},
#' \link{ggplot2.stripchart}, \link{ggplot2.boxplot}, \link{ggplot2.histogram},
#' \link{ggplot2.density}}
#' @references http://www.sthda.com
#' @examples
#'
#' #data
#' set.seed(1234)
#' df <- data.frame(grp = factor( rep(c("A","B"), each=200) ),
#'                    var = c(rnorm(200),rnorm(200, mean=.8)))
#'
#' #use ggplot2.customize to customize the plot
#' plot<-ggplot2.density(data=df, xName='var',groupName='grp', groupColors=c('#999999','#E69F00'))
#' print(plot)
#'
#' plot<-ggplot2.customize(plot, mainTitle="Plot of variable histogram \nper group",
#'                         xtitle="Variable", ytitle="Density")
#' print(plot)
#'
#' @export ggplot2.customize
ggplot2.customize<-function(plot,...)
{
  args=list(...)

  #Facets display subsets of the dataset in different panels.
  #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  if(!is.null(args$faceting)) faceting=args$faceting else faceting=FALSE
  if(!is.null(args$facetingVarNames)) facetingVarNames=args$facetingVarNames else facetingVarNames=NULL
  if(!is.null(args$facetingDirection)) facetingDirection=args$facetingDirection else facetingDirection="vertical"
  if(!is.null(args$facetingScales)) facetingScales=args$facetingScales else facetingScales="fixed"
  if(!is.null(args$facetingFont)) facetingFont=args$facetingFont else facetingFont=c(size=12, font="plain", color="black")
  if(!is.null(args$facetingRect)) facetingRect=args$facetingRect else facetingRect=list(background=NULL, lineType=NULL, lineColor=NULL, lineSize=NULL)
  if(!is.null(args$facetingTextAngles)) facetingTextAngles=args$facetingTextAngles else facetingTextAngles=c(NULL, NULL)
  if(faceting && !is.null(facetingVarNames)){
    #Faceting is done accoording to one variable
    if(length(facetingVarNames)==1){
      if(facetingDirection=="vertical")
        plot<-plot+ facet_grid(as.formula(paste(facetingVarNames," ~ .", sep='')), scales=facetingScales)
      else if(facetingDirection=="horizontal")
        plot<-plot+ facet_grid(as.formula(paste(". ~ ", facetingVarNames,sep='')), scales=facetingScales)
    }#end of if
    #Faceting is done accoording to 2 variables
    #first variable is vertical and second variable is horizontal
    else if(length(facetingVarNames)==2)
      plot<-plot+ facet_grid(as.formula(paste(facetingVarNames[1], "~ ", facetingVarNames[2],sep='')), scales=facetingScales)

  }


  # Background color
  #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  #Plot panel background color
  if(!is.null(args$backgroundColor)){
    backgroundColor<-args$backgroundColor
    if(backgroundColor%in%c("gray", "grey")) plot<-plot+theme_gray()#gray theme
    else if(backgroundColor=="white") plot<-plot+theme_bw()#black and white theme
    #for the other color
    else{
      plot<-plot+theme(
        panel.background=element_rect(fill=backgroundColor, size=0.5,
                                      linetype='solid',colour=backgroundColor) )
    }
  }

  #Facet label aperance
  #+++++++++++++++++++++++++++
  #Attention : should be here after backgroundColor modification => don't change the place
  #If you put the text before backgroundColor modification, the facet backgrount remain gray, even if
  #you indicate another color
  if(faceting && !is.null(facetingVarNames)){
    plot<-plot+theme(
      strip.text.x = element_text(size=facetingFont[1], face=facetingFont[2], color=facetingFont[3], angle=facetingTextAngles[1]),
      strip.text.y = element_text(size=facetingFont[1], face=facetingFont[2], color=facetingFont[3], angle=facetingTextAngles[2]),
      strip.background = element_rect(fill=facetingRect$background, colour=facetingRect$lineColor,
                                      linetype=facetingRect$lineType, size=facetingRect$lineSize)
    )
  }

  #Change axis default value accoording to call arguments
  #+++++++++++++++++++++++++++++++++++
  #x and y axis titles and scales
  if(!is.null(args$xShowTitle)) xShowTitle<-args$xShowTitle else xShowTitle=TRUE
  if(!is.null(args$yShowTitle)) yShowTitle<-args$yShowTitle else yShowTitle=TRUE
  if(!is.null(args$xtitle)) xtitle<-args$xtitle else xtitle=NULL
  if(!is.null(args$ytitle)) ytitle<-args$ytitle else ytitle=NULL
  if(!is.null(args$xtitleFont)) xtitleFont<-args$xtitleFont else xtitleFont=c(14,"bold", "black")
  if(!is.null(args$ytitleFont)) ytitleFont<-args$ytitleFont else ytitleFont=c(14,"bold", "black")
  if(!is.null(args$ylim)) ylim<-args$ylim else ylim=NULL
  if(!is.null(args$xlim)) xlim<-args$xlim else xlim=NULL
  if(!is.null(args$xScale)) xScale<-args$xScale else xScale=c("none", "log2", "log10")
  if(!is.null(args$yScale)) yScale<-args$yScale else yScale=c("none", "log2", "log10")
  #x and y axis tick mark labels
  if(!is.null(args$xShowTickLabel)) xShowTickLabel<-args$xShowTickLabel else xShowTickLabel=TRUE
  if(!is.null(args$yShowTickLabel)) yShowTickLabel<-args$yShowTickLabel else yShowTickLabel=TRUE
  if(!is.null(args$xTickLabelFont)) xTickLabelFont<-args$xTickLabelFont else xTickLabelFont=c(12, "bold", "black")
  if(!is.null(args$yTickLabelFont)) yTickLabelFont<-args$yTickLabelFont else yTickLabelFont=c(12, "bold", "black")
  if(!is.null(args$xtickLabelRotation)) xtickLabelRotation<-args$xtickLabelRotation else xtickLabelRotation=0
  if(!is.null(args$ytickLabelRotation)) ytickLabelRotation<-args$ytickLabelRotation else ytickLabelRotation=0
  if(!is.null(args$hideAxisTicks)) hideAxisTicks<-args$hideAxisTicks else hideAxisTicks=FALSE
  #axis line
  if(!is.null(args$axisLine)) axisLine<-args$axisLine else axisLine=c(0.5, "solid", "#E5E5E5")


  plot<-ggplot2.setAxis(plot, xShowTitle=xShowTitle, yShowTitle=yShowTitle,
                        xtitle=xtitle, ytitle=ytitle,
                        xtitleFont=xtitleFont, ytitleFont=ytitleFont,
                        xlim=xlim, ylim=ylim,xScale=xScale, yScale=yScale,
                        xShowTickLabel=xShowTickLabel, yShowTickLabel=yShowTickLabel,
                        xTickLabelFont=xTickLabelFont, yTickLabelFont=yTickLabelFont,
                        xtickLabelRotation=xtickLabelRotation, ytickLabelRotation=ytickLabelRotation,
                        hideAxisTicks=hideAxisTicks, axisLine=axisLine)

  # Customize main title
  #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  if(!is.null(args$mainTitle))plot<-plot+ggtitle(args$mainTitle)
  if(!is.null(args$mainTitleFont)) mainTitleFont=args$mainTitleFont
  else mainTitleFont=c(14, "bold", "black")
  plot<-plot+theme(plot.title=element_text(size=as.numeric(mainTitleFont[1]),
                                           lineheight=1.0, face=mainTitleFont[2], colour=mainTitleFont[3]))

  # plot Panel color and grid
  #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  #Plot panel grid color
  if(!is.null(args$gridColor)){
    gridColor=args$gridColor
    plot<-plot+theme(panel.grid.major=element_line(size=0.5, linetype='solid',colour=gridColor))+
      theme(panel.grid.minor=element_line(size=0.25, linetype='solid', colour=gridColor))
  }
  #remove top right border of the plot
  if(!is.null(args$removePanelBorder)){
    removePanelBorder=args$removePanelBorder
    if(removePanelBorder) plot<-plot+theme(panel.border=element_blank())
  }
  #Remove panel grid
  if(!is.null(args$removePanelGrid)){
    removePanelGrid=args$removePanelGrid
    if(removePanelGrid) plot<-plot+theme(panel.grid.minor=element_blank(),
                                         panel.grid.major=element_blank(),
                                         axis.line=element_line(size=as.numeric(axisLine[1]),
                                                                linetype=axisLine[2], colour=axisLine[3]))
  }

  # Legend
  #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  if(!is.null(args$showLegend)) showLegend=args$showLegend else showLegend=TRUE
  #possible values for legend position: legendPosition=c("right", "left","top", "bottom")
  #legendPosition can be also a numeric vector c(x, y) indicating the coordinate of legendBox
  #x and y values must be between 0 and 1. c(0,0) corresponds to "bottom left"
  #and  c(1,1) corresponds to "top right" position
  if(!is.null(args$legendPosition)) legendPosition=args$legendPosition else legendPosition ="right"
  if(showLegend==TRUE) plot<-plot+theme(legend.position=legendPosition)
  else plot<-plot+theme(legend.position='none')

  if(showLegend==TRUE){
    #+++++++legend background and text font style+++++
    #Legend background. legendBackground: c(boxFill, boxLineSize, boxLineType, boxLineColor)
    if(!is.null(args$legendBackground)) legendBackground=args$legendBackground
    else legendBackground=c("#FFFFFF", 0.5, "blank", "black")
    #Legend text font. legendTextFont=c(size, style, color)
    if(!is.null(args$legendTextFont)) legendTextFont=args$legendTextFont
    else legendTextFont=c(10, "plain", "black")
    #legendTitleFont=c(size, style, color)
    if(!is.null(args$legendTitleFont)) legendTitleFont=args$legendTitleFont
    else legendTitleFont=c(10, "bold", "black")
    plot<-plot+
      theme(legend.title=element_text(size=as.numeric(legendTitleFont[1]),
                                      face=legendTitleFont[2], colour=legendTitleFont[3]))+
      theme(legend.text=element_text(size=as.numeric(legendTextFont[1]),
                                     face=legendTextFont[2], colour=legendTextFont[3]))+
      theme(legend.background=element_rect(fill=legendBackground[1], size=as.numeric(legendBackground[2]),
                                           linetype=legendBackground[3], colour=legendBackground[4]))
    #legendTitle: title of legend
    if(!is.null(args$legendTitle)) plot<-plot+labs(fill=args$legendTitle, colour=args$legendTitle, shape=args$legendTitle)
    #legendItemOrder : character vector indicating the order of items in the legends.
    if(!is.null(args$legendItemOrder)) plot<-plot+scale_x_discrete(limits=as.character(args$legendItemOrder))
  }

  # Orientation of the plot
  #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  if(!is.null(args$orientation)) orientation=args$orientation else orientation="standard"
  if(orientation=="horizontal") plot<-plot+coord_flip()
  if(orientation=="yAxisReversed") plot<-plot+scale_y_reverse()

  plot
}
YTLogos/easyGgplot2 documentation built on May 3, 2019, 9:03 p.m.