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