2013-02-25 34 views
23

如何更改传说中符号的大小?我查了theme的文件,但没有找到答案。ggplot2:在传说中调整符号大小

下面是一个例子:

library(ggplot2);library(grid) 
set.seed(1000) 
x <- 1:6 
mu <- sin(x) 
observed <- mu + rnorm(length(x), 0, 0.5*sd(mu)) 
data <- data.frame(
    t=rep(x, 2), 
    value=c(mu, observed) - min(mu, observed) + 0.5, 
    class = rep(c("mu", "observed"), each=length(x))) 
mu <- data$value[1:length(x)] 
observed <- data$value[1:length(x) + length(x)] 
mu.min <- mu - 3 * 0.5 * sd(mu) 
mu.max <- mu + 3 * 0.5 * sd(mu) 
g <- ggplot(data=data) 
g <- g + geom_point(aes(x=value, y=t, shape=class, size=24)) + scale_size(guide="none") 
g <- g + scale_shape(name="", labels=expression(paste(S[u](t), ", the observation at time ", t), paste(mu[u](t), ", the mean of ", tilde(S)[u](t), "   "))) 
stat_function.color <- gray(0.5) 
g <- g + geom_segment(aes(y=1:6, yend=1:6, x=mu.min, xend=mu.max, linetype="2", alpha = 1), color=stat_function.color) + scale_alpha(guide="none") + scale_linetype(name= "", labels=expression(paste("probability density function (pdf) of ", tilde(S)[u], " at time ", t))) 
for(i in 1:length(x)) { 
    g <- g + stat_function(fun=function(x, i) { 
    ifelse(x <= mu.max[i] & x >= mu.min[i], dnorm(x, mu[i], sd(mu)) + i, NA) 
    }, color=stat_function.color, args=list(i=i)) 
} 
background.color <- gray(0.75) 
g <- g + theme(
    axis.text=element_blank(), 
    title=element_text(size=rel(1.5)), 
    legend.text=element_text(size=rel(1.5)), 
    legend.position="top", 
    legend.direction="vertical", 
# legend.key.size = unit(2, "cm"), 
    panel.background=element_rect(fill=background.color), 
    panel.grid.major=element_line(color=background.color), 
    panel.grid.minor=element_line(color=background.color) 
) + coord_flip() 
plot(g) 
+1

看到http://stackoverflow.com/questions/16356052/control-ggplot2-legend-look-without-affecting -the-plot – PatrickT 2014-12-23 12:05:35

回答

37

您可以通过这些种类的手动使用override.aes参数guide_legend()变化:

g <- g + guides(shape = guide_legend(override.aes = list(size = 5))) 
print(g) 
17

你应该使用:

theme(legend.key.size = unit(3,"line")) 
+3

恕我直言,这是更合适的答案,因为它使用问题中提到的“主题”。 – 2017-02-16 18:04:27

+1

这段代码增加了符号周围的区域,而不是符号本身。指南代码更合适。 – LindsayLucas 2017-08-18 20:22:58

4

马吕斯的答案在R 3.2.2版本中对我无效。您仍然可以使用相同的override.eas参数呼叫guide_legend(),但是您将需要在包装函数中指定color而不是shape

所以,如果你正在运行R的更新版本,试试这个来代替:

g + guides(color = guide_legend(override.aes = list(size=5)))