首页 文章

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

提问于
浏览
9

我想在下面的ggplot中调整线型 . 因此,我在data.frame df中引入另一列来表示线型,但是一旦我将其转换为因子,线型而不是“方法”出现在图例中......(参见试验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)

1 回答

  • 16

    使用 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))
    

    enter image description here

相关问题