在ggplot中锁定图例的大小和位置

时间:2018-01-24 16:08:57

标签: r plot ggplot2 legend

缩放或更改图形的宽度和长度时,图例会自动更改大小。通过使用注释添加文本和段,原始位置将丢失。我该如何解决这个问题?

示例代码:

library(reshape2)
library(dplyr)
library(ggplot2)
A <- matrix(c(2 ,   0   ,   0   ,   0   ,   0   ,   2   ,
          0 ,   0   ,   0   ,   0   ,   2   ,   2   ,
          0 ,   0   ,   0   ,   0   ,   3   ,   2   ,
          0 ,   0   ,   0   ,   0   ,   0   ,   6   ,
          2 ,   2   ,   3   ,   5   ,   4   ,   2   ,
          6 ,   4   ,   3   ,   0   ,   0   ,   0   ,
          0 ,   0   ,   3   ,   1   ,   0   ,   0   ,
          0 ,   0   ,   0   ,   2   ,   2   ,   1   ,
          0 ,   0   ,   2   ,   3   ,   0   ,   0   ,
          0 ,   2   ,   2   ,   0   ,   0   ,   0), nrow=10, ncol=6, byrow = T)
rownames(A) <- paste("x", 1:10, sep="")
colnames(A) <- paste("y", 1:6, sep="")
longData <- melt(A)
longData$Var1 <- factor(longData$Var1, levels=names(sort(rowSums(A),             decreasing = T)))
longData$Var2 <- factor(longData$Var2, levels=names(sort(colSums(A), decreasing = T)))

longData<-longData[longData$value!=0,]

ggplot(longData, aes(x = Var2, y = Var1)) +     geom_raster(aes(fill=value)) + 
scale_fill_gradientn(colours=c("#180052", "#0c0083","#0000b4",     "#0000e4","#0010ff", "#0041ff", "#0072ff", "#00A3FF", "#00D4FF", "#00FF49", "#5AFF00", "#FFE400", "#FFC400", "#FFA300", "#FF8300", "#FF6200", "#FF4100", "#FF2100", "#FF0000", "#E40000"), 
                     values=c(0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1), breaks=seq(0,1,0.2),  limits=c(0,1), 
                 guide = guide_colorbar(title="Value", title.position = "right", title.hjust = 0.5,  title.theme = element_text(angle = 90, size = 9), barwidth= 2, barheight = 10)) + 
  theme_void() +
  annotate("text", x = c(7.1,7.1), y = c(7,4), label = c("increase", "decrease") , size=4 , angle=90) +
  annotate("segment", x = 7.3, xend = 7.3, y = 5, yend = 2, colour = "black", size=1, alpha=0.6, arrow=arrow()) +
  annotate("segment", x = 7.3, xend = 7.3, y = 6, yend = 9, colour = "black", size=1, alpha=0.6, arrow=arrow()) 

Here is the graph with the default resolution

Here is the graph with the width 900 and height 755

0 个答案:

没有答案