如何刻度线的大小和GGPLOT2
的代码如下:如何刻度线的大小和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)
,结果是这样的:
点的大小太小所以我想通过scale_size
改变它的大小。但是,似乎线条和点都受到了影响。所以我想知道是否有一种方法可以用单独的图例分别缩放线条和点?
我能想到的两种方式是1)结合两个传奇grobs或2)黑客另一个传奇审美。 @Mike Wise在上面的评论中都提到了这两点。
方法1:结合使用grobs在同一地块中的2个独立的传说。
我用这个answer的代码来抓取图例。巴蒂斯特的arrangeGrob vignette是一个有用的参考。
为 printinglibrary(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)情节。
方法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)))))
这就是我需要。谢谢! – Tiger
另一个问题是,如果我在**方法#2 **中设置'range = c(1,3)','size'将同时控制线和点,那么如何分别控制它们? @oshun – Tiger
你不行。如果您想要更多的控制,请使用方法1.如果您想使用方法2,则对于点和线都将保持相同的比例。请注意,解决方案#2通过乘以100将点(范围= 2到10)转换为与线(范围140-905)相同的比例。要相对于彼此更改它们的大小,请更改此比例因子。尝试点数* 50(相对于线条的较小点数)或点数* 200(较大的点数)。将缩放范围缩小到c(1,3),将转换大小限制在1-3之间,这似乎适得其反。为什么不增加可能的尺寸范围? – oshun
只有一种尺寸的传说。如果你想拥有不同的图例,你需要为其中一个或另一个使用别的东西,比如'linetype'或'color'。 –
如果对于点大小= z * 100' – mtoto
是否可以创建另一个大小的图例?也许对于这个简单的例子,它可以被'linetype'或'color'取代,但是如果'linetype'或'color'已经被使用或者不适合该图,那么我们仍然需要解决这个问题。 @MikeWise – Tiger