2016-01-20 242 views
12
分別指向

的代碼如下:如何刻度線的大小和GGPLOT2

set.seed(123) 
d1=data.frame(x=runif(10),y=runif(10),z=runif(10,1,10)) 
d2=data.frame(x=runif(10),y=runif(10),z=runif(10,100,1000)) 
ggplot()+geom_point(aes(x,y,size=z),data=d1)+ 
geom_line(aes(x,y,size=z),data=d2) 

,結果是這樣的:

enter image description here

點的大小太小所以我想通過scale_size改變它的大小。但是,似乎線條和點都受到了影響。所以我想知道是否有一種方法可以用單獨的圖例分別縮放線條和點?

+2

只有一種尺寸的傳說。如果你想擁有不同的圖例,你需要爲其中一個或另一個使用別的東西,比如'linetype'或'color'。 –

+3

如果對於點大小= z * 100' – mtoto

+0

是否可以創建另一個大小的圖例?也許對於這個簡單的例子,它可以被'linetype'或'color'取代,但是如果'linetype'或'color'已經被使用或者不適合該圖,那麼我們仍然需要解決這個問題。 @MikeWise – Tiger

回答

3

我能想到的兩種方式是1)結合兩個傳奇grobs或2)黑客另一個傳奇審美。 @Mike Wise在上面的評論中都提到了這兩點。

方法1:結合使用grobs在同一地塊中的2個獨立的傳說。

我用這個answer的代碼來抓取圖例。巴蒂斯特的arrangeGrob vignette是一個有用的參考。

printing
library(grid); library(gridExtra) 

#Function to extract legend grob 
g_legend <- function(a.gplot){ 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    legend 
} 

#Create plots 
p1 <- ggplot()+ geom_point(aes(x,y,size=z),data=d1) + scale_size(name = "point") 
p2 <- ggplot()+ geom_line(aes(x,y,size=z),data=d2) + scale_size(name = "line") 
p3 <- ggplot()+ geom_line(aes(x,y,size=z),data=d2) + 
     geom_point(aes(x,y, size=z * 100),data=d1) # Combined plot 
legend1 <- g_legend(p1) 
legend2 <- g_legend(p2) 
legend.width <- sum(legend2$width) 

gplot <- grid.arrange(p3 +theme(legend.position = "none"), legend1, legend2, 
      ncol = 2, nrow = 2, 
      layout_matrix = rbind(c(1,2), 
            c(1,3)), 
      widths = unit.c(unit(1, "npc") - legend.width, legend.width)) 
grid.draw(gplot) 

注:使用arrangeGrob()代替grid.arrange()。我不得不使用png; grid.draw; dev.off來保存(arrangeGrob)情節。

grob_legends

方法2:黑客另一個審美的傳奇。

MilanoR在這方面有一個很棒的帖子,專注於顏色而不是尺寸。 更多舉例:1)discrete colour和2)colour gradient

#Create discrete levels for point sizes (because points will be mapped to fill) 
d1$z.bin <- findInterval(d1$z, c(0,2,4,6,8,10), all.inside= TRUE) #Create bins 

#Scale the points to the same size as the lines (points * 100). 
#Map points to a dummy aesthetic (fill) 
#Hack the fill properties. 
ggplot()+ geom_line(aes(x,y,size=z),data=d2) + 
    geom_point(aes(x,y, size=z * 100, fill = as.character(z.bin)),data=d1) + 
    scale_size("line", range = c(1,5)) + 
    scale_fill_manual("points", values = rep(1, 10) , 
        guide = guide_legend(override.aes = 
           list(colour = "black", 
           size = sort(unique(d1$z.bin))))) 

legend_hack

+0

這就是我需要。謝謝! – Tiger

+0

另一個問題是,如果我在**方法#2 **中設置'range = c(1,3)','size'將同時控制線和點,那麼如何分別控制它們? @oshun – Tiger

+0

你不行。如果您想要更多的控制,請使用方法1.如果您想使用方法2,則對於點和線都將保持相同的比例。請注意,解決方案#2通過乘以100將點(範圍= 2到10)轉換爲與線(範圍140-905)相同的比例。要相對於彼此更改它們的大小,請更改此比例因子。嘗試點數* 50(相對於線條的較小點數)或點數* 200(較大的點數)。將縮放範圍縮小到c(1,3),將轉換大小限制在1-3之間,這似乎適得其反。爲什麼不增加可能的尺寸範圍? – oshun

相關問題