gpt4 book ai didi

r - 在ggplot2中向图例添加线型

转载 作者:行者123 更新时间:2023-12-02 09:18:16 24 4
gpt4 key购买 nike

如何使 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。此几何图形默认为 FALSE,这可能很直观,也可能不直观。 (我明白其中的道理。)

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com