2016-06-13 5 views
1

나는 ggplot2의 geom_tile 함수를 사용하여 dataset의 시각화를 작성합니다. 나는 그것에 거의 만족하지만, 나는 그것에 특별한 전설을 추가하고 싶지만, 나는 이것을위한 적절한 방법을 찾을 수 없었다. 나는 그 게시물에서 정확히 나중에 무슨 뜻인지 설명 할 것이다.범주에 따라 수동 범례 ggplot2 플롯

내가 현재 사용하고있는 코드는 다음과 같습니다. R에 익숙하지 않아 시행 착오를 거쳐이 코드가 생성되었습니다. 누군가 그것을 기꺼이 치우려고한다면, 자신을 노크하십시오 :-).

#Read source data 
meta <- read.csv("Dropbox/meta_censored.csv") 

#import libraries 
library("ggplot2") 
library("plyr") 
library("reshape2") 
library("scales") 
library("grid") 

#transform and rescale data in prep for later steps 
meta.m <- melt(meta) 
meta.s <- ddply(meta.m, .(variable), transform, 
       rescale = scale(value)) 


#generate categories to sort conditions by colour 
meta.s$Category <- meta.s$variable 
levels(meta.s$Category) <- 
    list("1_early" = c("X1", "X2"), 
     "2_early" = c("X3", "X4", "X5", "X6", "X7"), 
     "1_late" = c("X10", "X17"), 
     "2_late" = c("X8", "X9", "X11", "X12", "X14", "X15", "X16"), 
     "3_late" = "X13", 
     "4_late" = c("X18", "X19")) 

#define colours per category 
meta.s$rescaleoffset <- meta.s$rescale + 100*(as.numeric(meta.s$Category)-1) 
scalerange <- range(meta.s$rescale) 
gradientends <- scalerange + rep(c(0,100,200,300,400,500), each = 2) 
colorends <- c("white", "red", "white", "green", "white", "red", "white", "green", "white", "orange", "white", "purple") 

#reorder by category 
meta.s$variable2 <- reorder(meta.s$variable, as.numeric(meta.s$Category)) 

#reverse y axis labels (were z-a, now a-z) 
flevels <- levels(meta.s$Param) 
flevels <- rev(flevels) 

#x axis annotation variables 
text_early <- textGrob("Early", gp=gpar(fontsize = 5, fontface = "bold", col = "red")) 
text_late <- textGrob("Late", gp=gpar(fontsize = 5, fontface = "bold", col = "red")) 

#plot heatmap 
p <- ggplot(meta.s, aes(variable2, Param)) + 
    geom_tile(aes(fill = rescaleoffset), colour = "lightgrey") + 
    #add line to seperate early from late 
    geom_vline(xintercept = 7.5) + 
    scale_fill_gradientn(colours = colorends, values = rescale(gradientends)) + 
    scale_x_discrete("", expand = c(0, 0)) + 
    scale_y_discrete("", limits = flevels, expand = c(0, 0)) + 
    theme_grey(base_size = 5) + 
    theme(legend.position = "right", 
     axis.ticks = element_blank(), 
     axis.text.x = element_text(angle = 270, hjust = 0, size = 5, vjust = 0, face = "bold"), 
     plot.margin = unit(c(1,1,2,1), "lines")) + 
    annotation_custom(text_early, xmin = 0, xmax = 8, ymin=168.5, ymax = 168.5) + 
    annotation_custom(text_late, xmin = 8, xmax = 19, ymin=168.5, ymax = 168.5) 

gt <- ggplot_gtable(ggplot_build(p)) 
gt$layout$clip[gt$layout$name == "panel"] <- "off" 
grid.draw(gt) 

기본적으로 x 축의 각 값에 의해 Param 열의 개체 당 값을 표시하려고합니다. x 축의 각 값은 다른 실험 조건을 가진 다른 연구를 나타냅니다. this thread을 사용하여 그룹화를 시도했지만 각 그룹마다 다른 색상이 적용됩니다.

이제 내가 원하는 것은 범례가 각 범주의 개별 단색을 표시하고 각 셀의 값을 기반으로하는 전체 그래디언트가 아니라는 것입니다. 물론 이 ggplot2로 생성 된 범례 일 필요는 없으며, 다른 방법은 트릭을 수행하는 한 허용됩니다.

미리 감사드립니다.

답변

0

shape = Category (효과가 없으므로 플롯의 모양이 변경되지 않음)을 포함하고 override.aes을 사용하여 각 카테고리의 색상을 얻을 수 있습니다. 4 개의 카테고리 만 원할 경우 substr을 사용하여 숫자 (첫 번째 요소)를 기준으로 채우기 색상을 정의 할 수 있습니다. 그라데이션 전설을 제거하기 위해 당신은 추가 할 수 있습니다 guide = FALSEscale_fill_gradientn에 :

ggplot(meta.s, aes(variable2, Param)) + 
    geom_tile(aes(fill = rescaleoffset, shape = substr(Category, 1, 1)), colour = "lightgrey", show.legend = TRUE) + 
    #add line to seperate early from late 
    geom_vline(xintercept = 7.5) + 
    scale_fill_gradientn(colours = colorends, values = rescale(gradientends), guide = FALSE) + 
    scale_x_discrete("", expand = c(0, 0)) + 
    scale_y_discrete("", limits = flevels, expand = c(0, 0)) + 
    theme_grey(base_size = 5) + 
    theme(legend.position = "right", 
     axis.ticks = element_blank(), 
     axis.text.x = element_text(angle = 270, hjust = 0, size = 5, vjust = 0, face = "bold"), 
     plot.margin = unit(c(1,1,2,1), "lines")) + 
    annotation_custom(text_early, xmin = 0, xmax = 8, ymin=168.5, ymax = 168.5) + 
    annotation_custom(text_late, xmin = 8, xmax = 19, ymin=168.5, ymax = 168.5) + 
    guides(shape = guide_legend("Category", override.aes = list(fill = c("red", "green", "orange", "purple")))) 

enter image description here