ggplot_commons.R 6.26 KB
Newer Older
1
2
#require_auto(ggplot2)
#require_auto(scales)
Holger Brandl's avatar
Holger Brandl committed
3

Holger Brandl's avatar
Holger Brandl committed
4
5
6

scale_fill_redgreed <- function() scale_fill_manual(values = c("red","darkgreen"))

Holger Brandl's avatar
Holger Brandl committed
7
rot_x_lab <- function() theme(axis.text.x = element_text(angle = 90, hjust = 1))
8
rot_x_45 <- function() theme(axis.text.x = element_text(angle = 45, hjust = 1))
Holger Brandl's avatar
Holger Brandl committed
9
## DEPRACTED because of naming
Holger Brandl's avatar
Holger Brandl committed
10
11
12
rotXlab <- function() theme(axis.text.x = element_text(angle = 90, hjust = 1))


Holger Brandl's avatar
Holger Brandl committed
13
14
15
16
17
18
# allow for layer-wise subsetting
# http://stackoverflow.com/questions/35806310/ggplot-plotting-layers-only-if-certain-criteria-are-met
pick <- function(condition){
    function(d) d %>% filter_(condition)
}

Holger Brandl's avatar
Holger Brandl committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols:   Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, by.row=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {

  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                    ncol = cols, nrow = ceiling(numPlots/cols))
  }

 if (numPlots==1) {
    print(plots[[1]])

  } else {
    # Set up the page
Holger Brandl's avatar
Holger Brandl committed
51
52

    grid::grid.newpage()
Holger Brandl's avatar
Holger Brandl committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}


gg2Format="png"

Holger Brandl's avatar
Holger Brandl committed
69
70

## simplified save function for ggpltos
Holger Brandl's avatar
Holger Brandl committed
71
ggsave2 <- function(gplot=last_plot(), width=8, height=6, prefix="", saveData=FALSE, outputFormat=gg2Format, ...){
Holger Brandl's avatar
Holger Brandl committed
72
    title <- try(gplot$labels[["title"]])
Holger Brandl's avatar
Holger Brandl committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

    if(is.null(title)){
        varMapping <- gplot$labels
        varMapping <- varMapping[names(varMapping) %in% c("x", "y")]
#        if(varMapping==NULL){
#            varMapping <- gplot$mapping;
#        }

        if(length(varMapping) == 1){
            title= paste("distribution of", varMapping)
        }else{
            title = try(paste(varMapping, collapse=" vs "))
        # stop("last plot had no title. Use ggsave() and give it a manual title")
        }

        rawFacetDesc <- format(gplot$facet)
        if(rawFacetDesc!="facet_null()"){
Holger Brandl's avatar
Holger Brandl committed
90
            title <- paste(title, "by", str_replace_all(str_match(rawFacetDesc, "facet_.*[(](.*)[)]")[,2], "~", "and"))
Holger Brandl's avatar
Holger Brandl committed
91
92
93
94
        }
    }


Holger Brandl's avatar
Holger Brandl committed
95
    fileBaseName <- ifelse(nchar(prefix)>0, paste0(prefix, " - ", title), title)
Holger Brandl's avatar
Holger Brandl committed
96
97
98
99

    ## clean up weired characters
    fileBaseName <- str_replace_all(fileBaseName, "[$%/?]", "_")

Holger Brandl's avatar
Holger Brandl committed
100
    fileName = paste0(fileBaseName, paste0(".", outputFormat))
Holger Brandl's avatar
Holger Brandl committed
101
102
103
104
105
106
107

    ## remove line-breaks and trim spaces
    fileName = str_replace_all(str_replace_all(fileName, "\\n", ""), "[ ]{2,}", " ")
#    print(paste("saving plot to ", fileName))
    ggsave(fileName, width=width, height=height, ...)

    if(saveData){
Holger Brandl's avatar
Holger Brandl committed
108
        write.delim(gplot$data, file= paste0(fileBaseName, ".txt"))
Holger Brandl's avatar
Holger Brandl committed
109
110
111
112
113
    }

    return(fileName)
}

114
115
116
## toggle active output device (see ggplot_devel.R for auto-toggeling plot)
toggle_plot_window = function() dev.set(dev.next())

Holger Brandl's avatar
Holger Brandl committed
117
118
119
120

########################################################################################################################
### pca plots (http://largedata.blogspot.de/2011/07/plotting-pca-results-in-ggplot2.html)

Holger Brandl's avatar
Holger Brandl committed
121
122
123
124
125
makePcaPlot = function(matrixData, group = NA, items=rownames(matrixData), title = NA) {
  load_pack(ggplot2)
  load_pack(RColorBrewer)

  mydata.pca = prcomp(matrixData, retx=TRUE, center=TRUE, scale.=TRUE)
Holger Brandl's avatar
Holger Brandl committed
126
127
128
129
130
131
132

  percent <- round((((mydata.pca$sdev)^2 / sum(mydata.pca$sdev^2))*100)[1:2])

  scores <- mydata.pca$x
  pc12 <- data.frame(PCA1=scores[,1], PCA2=scores[,2], group=group)

#  ggplot(pc12, aes(PCA1, PCA2, colour = group)) + geom_point(size = 6, alpha = 3/4)
Holger Brandl's avatar
Holger Brandl committed
133
  pcaPlot = ggplot(pc12, aes(PCA1, PCA2, color=group, label=items)) +
Holger Brandl's avatar
Holger Brandl committed
134
135
136
137
138
139
140
    geom_point(alpha = .4)   +
#    geom_text(hjust = "inward", alpha = 3/4)    +
    geom_text(alpha = 3/4, vjust=1.5)    +
    ## make labels to be rendered within canvas bounds --> "inward" is better
    ## https://stackoverflow.com/questions/17241182/how-to-make-geom-text-plot-within-the-canvass-bounds#
    scale_x_continuous(expand = c(.2, .2)) +

Holger Brandl's avatar
Holger Brandl committed
141
142
143
    xlab(paste("PCA1 (", percent[2], "%)", sep = "")) +
    ylab(paste("PCA2 (", percent[2], "%)", sep = ""))

Holger Brandl's avatar
Holger Brandl committed
144
145
146
147
148

    if(!is.na(title))
        pcaPlot = pcaPlot + ggtitle(title)

    pcaPlot
Holger Brandl's avatar
Holger Brandl committed
149
150
151
152
153
}


## example
# makePcaPlot(getData(30,4,2,distort = 0.7))
Holger Brandl's avatar
Holger Brandl committed
154
155


Holger Brandl's avatar
Holger Brandl committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
########################################################################################################################
### ggpairs

#load_pack(GGally)
#ggpairs(tips, mapping = aes(color = sex), columns = c("total_bill", "time", "tip"))

gp_alpha <- function(data, mapping, ...) {
    ggplot(data = data, mapping=mapping) + geom_point(alpha = 0.1)
}

gp_bin2d <- function(data, mapping, ..., low = "#10721C", high = "#F11D05") {
    ggplot(data = data, mapping = mapping) +
    geom_bin2d(...) +
    scale_fill_gradient(low = low, high = high)
}
#qModelStats %>% ungroup() %>% select(-ensembl_gene_id) %>% ggpairs(lower=list(continuous=gp_bin2d), title="plot score as regressor")



Holger Brandl's avatar
Holger Brandl committed
175
176
177
178
########################################################################################################################
### Base-plot utils


Holger Brandl's avatar
Holger Brandl committed
179
plotPDF <- function(fileBaseName, expr, ...){ pdf(paste0(fileBaseName, ".pdf"), ...); expr; dev.off(); }
Holger Brandl's avatar
Holger Brandl committed
180
181
#plotPDF("test", plot(1:10))

182
183
184
185

## create a custom color palette for a fixed set of values
## scale_fill_manual(values = create_palette(unique(csWithTopoT1$t1_type)), drop = FALSE)
create_palette <- function(x, pal = 'Set1'){
Holger Brandl's avatar
Holger Brandl committed
186
  loadpack(RColorBrewer)
187

188
189
  ux <- sort(unique(x))
  n <-length(ux)
190
191
192

  if(n==0) return(c())

193
194
195
  setNames(brewer.pal(name = pal, n = n)[1:n], ux)
}