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

最佳答案

您浏览了几个示例,但是这个简单的案例应该可以帮助您完成大部分工作:

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 创建图例,这会导致在幕后创建一个新列。使用创建列并将它们映射到线型的常用方法,多种线型应该可以正常工作。

关于r - 在ggplot2中向图例添加线型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16902204/

10-12 22:33