在ggplot2中为图例添加线型

时间:2013-06-03 17:14:57

标签: r ggplot2 legend

如何让geom_hline或geom_abline使用的线型出现在ggplot图的图例中?

例如:

require (ggplot2)

# some data
dummy <- data.frame (category1 =  rep (1:5, 8), category2 = rep (1:4, each = 10), 
    category3 = rep (factor (1:2), 2), expected = 10 ^ rep (4:7, each = 10),
    value = 10 ^rnorm(40, 5))

# faceted plot
baseplot <-ggplot (dummy ) +
    geom_point (aes (category1, value, color = category3))+
    scale_y_log10 () + 
    facet_wrap (~category2)

# add a dotted line for expected value
p1 <-baseplot + geom_hline ( aes ( yintercept = expected), linetype = 2)

我尝试了几种让虚线显示在图例中的方法,但它们给了我与p1相同的东西

p1a < -p1+scale_linetype_discrete (labels = "expected")+
    guides ( linetype= guide_legend ("", labels ="expected"))
p1b <- baseplot + geom_hline (aes (yintercept = expected, linetype = "expected")) +
    scale_linetype_manual (labels= "expected", values = 2)
p1a
p1b

多行/行类型怎么样?

假设我也想绘制分组和整体几何平均值

require (reshape)
require (plyr)

# calculate geometric means, keep them in their own data frame
geometric_mean <- function (x)  exp ( mean (log (x)))
dummy $GM_overall <- geometric_mean (dummy $value)
extra <- ddply(dummy, c( "GM_overall", "expected","category2"), summarize,
    GM_group = geometric_mean (value))
extra_long <- melt (GM_group_long, id.vars = "category2")

我希望这种方法能够根据this post在图例中显示线型,但没有这样的运气

p2=baseplot + geom_hline ( aes ( yintercept = value , linetype = variable), extra)
p2

这是另一个我希望用abline做类似事情的案例

能够将该行标记为1:1

会很高兴
dummy$value2 <- dummy $value * runif(40, 0.5, 2)
ggplot (dummy)+coord_fixed() +    
    geom_point (aes (value, value2, color = category3))+
    geom_abline (yintercept =0, slope =1) 

我正在使用R 3.0.0,ggplot 0.9.3.1

1 个答案:

答案 0 :(得分:3)

你经历了几个例子,但是这个简单的案例应该可以让你大部分时间:

dummy <- data.frame (category1 =  rep (1:5, 8), category2 = rep (1:4, each = 10), 
    category3 = rep (factor (1:2), 2), expected = 10 ^ rep (4:7, each = 10),
    value = 10 ^rnorm(40, 5))

# faceted plot
baseplot <- ggplot(dummy) +
    geom_point(aes(category1, value, color = category3))+
    scale_y_log10() + 
    facet_wrap(~category2)

# add a dotted line for expected value
baseplot + geom_hline(aes(yintercept = expected,linetype = "expected"),show_guide = TRUE)

我认为,在大多数情况下,关键是添加show_guide = TRUE。对于此geom,默认为FALSE,这可能是也可能不直观。 (我可以看到理由。)

请注意,在这种“单行类型”的情况下,我“欺骗”ggplot通过映射线型创建一个图例到“expected”字符,这会导致在后面创建一个新列场景。多行类型应该按照预期的方式使用创建列并将它们映射到线型的常用方法。