Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Legend does not show all categories even with drop=FALSE

Tags:

r

ggplot2

I have a p-value matrix (pvalmat) and I want to draw a tile graph to depict different ranges of p-values. Previously on stackoverflow, people have noted drop=FALSE argument would be sufficient for retaining all the categories in the tile graph. Yet it doesn't work for me.

The code I use is as follows:

library(reshape)
library(ggplot2)

t1 <- "
                         PC1        PC2       PC3        PC4       PC5
Sample_Group       0.8736898 0.97622168 0.2561840 0.42037376 0.1014430
Patient_ID         0.5715401 0.11196997 0.7373194 0.29259420 0.4492927
Batch              0.2372638 0.31829279 0.6886578 0.13898381 0.8962650
Gender             0.2849828 0.19308078 0.7906396 0.70711634 0.1862483
Race               0.9625020 0.86909694 0.9539444 0.45216929 0.4484681
Vital_Status       0.6132153 0.59893269 0.1587745 0.77892172 0.7018237
Family_History     0.5434387 0.19100356 1.0000000 0.20342504 0.8735441
Tissue_Source_Site 0.5448434 0.06034538 0.2239321 0.03223223 0.9604476
Initial_Weight     0.3545216 0.42727010 0.3310045 0.72190824 0.5736651
Age                0.5180032 0.28494126 0.4975151 0.37259105 0.4632363
"

con <- textConnection(t1)
pvalmat <- read.table(con, row.names = NULL)   

pvalmat.m <- melt(pvalmat)
colnames(pvalmat.m) <- c("Clinical_Variables", "Principal_Component", "pval")
pvalmat.m$colorcut <- cut(pvalmat.m$pval,breaks = c(-Inf,0.001, 0.01, 0.05, 0.1, Inf), right = FALSE)

p <- ggplot(pvalmat.m, aes(Principal_Component, Clinical_Variables)) + geom_tile(aes(fill = colorcut), colour = "white") + 
  scale_fill_manual(breaks=c("[-Inf, 0.001)", "[0.001, 0.01)", "[0.01, 0.05)", 
                             "[0.05, 0.1)", "[0.1, Inf)"),
                    values = c("darkred", "red", "orange", "yellow", "gray"),
                    name="P-value", labels=c("< 0.001", "< 0.01", "< 0.05", "< 0.1", "> 0.1"), 
                    drop=FALSE) + 
  labs(x="Principal Components", y="Clinical Variables")

Yet i receive only one category in the legend:

P-value plot

Although it shows the colors correctly, why it is not showing the legend with all categories?

Thanks!

like image 498
jatha Avatar asked Jun 08 '16 09:06

jatha


1 Answers

You have already broken pval into discrete categories so you do not need to do so again in scale_fill_manual.

ggplot(pvalmat.m, aes(Principal_Component, Clinical_Variables)) + 
  geom_tile(aes(fill = colorcut), colour = "white") + 
  scale_fill_manual(values = c("darkred", "red", "orange", "yellow", "gray"), 
                    drop = FALSE,
                    name="P-value", 
                    labels=c("< 0.001", "< 0.01", "< 0.05", "< 0.1", "> 0.1"))

enter image description here

like image 148
timcdlucas Avatar answered Nov 05 '22 12:11

timcdlucas