3

如何使 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")

我希望这种方法可以根据这篇文章在图例中显示线型,但没有这样的运气

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

4

1 回答 1

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. 默认情况FALSE下,此几何图形可能直观,也可能不直观。(我可以看到理由。)

请注意,在这种“一种线型”的情况下,我如何通过将线型映射到“预期”字符来“欺骗”ggplot 创建一个图例,这会导致在幕后创建一个新列。使用创建列并将它们映射到线型的常用方法时,多种线型应按预期工作。

于 2013-06-03T17:58:45.957 回答