ggplot2:如何调整线型+图例顺序?

10

我想要调整以下ggplot中的线型。因此,我在数据框df中引入了另一列来表示线型,但一旦将其转换为因子,图例中出现了代表线型而非“方法”的线型(参见Trial 3)。

我该如何在图例中获取“method”?最终我希望能够:

  1. 自由选择线型,
  2. 自由选择这些线型在图例中出现的顺序,和
  3. 将相应的“method”显示为图例文本。

以下是我的尝试:

require(ggplot2)
set.seed(1)
df <- data.frame(x=c(1:4, 2:5),
                 method=rep(c("a", "b"), each=4),
                 lt=rep(c(5,3), each=4),
                 value=rep(c(0,1), each=4)+runif(8))

## trial 1:
ggplot(df, aes(x=x, y=value)) + 
   geom_point() + 
   geom_line(aes(group=method, linetype=method)) 
# fine, but not the linetypes I would like to have

## trial 2:
ggplot(df, aes(x=x, y=value)) + 
   geom_point() + 
   geom_line(aes(group=method, linetype=lt)) 
# correct linetypes, but no legend

## trial 3:
ggplot(df, aes(x=x, y=value)) + 
   geom_point() + 
   geom_line(aes(group=method, linetype=as.factor(lt))) 
# legend, but not the correct one (I would like to have the "group"ing 
# variable "method" in the legend as in trial 1)

“+ scale_linetype(name = "Method")” 似乎在第三次尝试中有效。 - Chase
这给了我图例标题“方法”,但仍然得到“3”和“5”作为图例文本,而不是试验1中的“a”和“b”。 - Marius Hofert
1个回答

17

使用method作为linetype,然后手动映射它到你想要的线条类型。这样就不需要引入另一个变量了。

ggplot(df, aes(x=x, y=value)) +
    geom_point() +
    geom_line(aes(linetype=method)) +
    scale_linetype_manual(breaks=c("a","b"), values=c(5,3))

这里输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接