【问题标题】:How to add ggplot legend of two different lines R?如何添加两条不同线R的ggplot图例?
【发布时间】:2013-10-03 18:59:32
【问题描述】:

我需要在我的两个地块的顶部添加两条线(最佳拟合线和 45 度线)的图例。对不起,我不知道如何添加情节!请帮帮我,我真的很感激!!!!

这是一个例子

type=factor(rep(c("A","B","C"),5))
xvariable=seq(1,15)
yvariable=2*xvariable+rnorm(15,0,2)
newdata=data.frame(type,xvariable,yvariable)
p = ggplot(newdata,aes(x=xvariable,y=yvariable))
p+geom_point(size=3)+ facet_wrap(~ type) +
  geom_abline(intercept =0, slope =1,color="red",size=1)+ 
  stat_smooth(method="lm", se=FALSE,size=1)

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    这是另一种方法,它使用美学映射到字符串常量来识别不同的组并创建图例。

    首先是另一种创建测试数据的方法(并将其命名为 DF 而不是 newdata

    DF <- data.frame(type = factor(rep(c("A", "B", "C"), 5)),
                     xvariable = 1:15,
                     yvariable = 2 * (1:15) + rnorm(15, 0, 2))
    

    现在是ggplot 代码。请注意,对于geom_ablinestat_smoothcolour 被设置在内部,aes 调用这意味着使用的两个值中的每一个都将映射到不同的颜色,并为此创建一个指南(图例)映射。

    ggplot(DF, aes(x = xvariable, y = yvariable)) +
      geom_point(size = 3) + 
      geom_abline(aes(colour="one-to-one"), intercept =0, slope = 1, size = 1) +
      stat_smooth(aes(colour="best fit"), method = "lm", se = FALSE, size = 1) + 
      facet_wrap(~ type) +
      scale_colour_discrete("")
    

    【讨论】:

    • @Henrik 通常当一个美学被映射到一个字符串常量时,这是用户部分的错误,因为意图是设置而不是映射,美学。但这里确实需要映射。
    【解决方案2】:

    试试这个:

    # original data
    type <- factor(rep(c("A", "B", "C"), 5))
    x <- 1:15
    y <- 2 * x + rnorm(15, 0, 2)
    
    df <- data.frame(type, x, y)
    
    # create a copy of original data, but set y = x
    # this data will be used for the one-to-one line
    df2 <- data.frame(type, x, y = x)
    
    # bind original and 'one-to-one data' together
    df3 <- rbind.data.frame(df, df2)
    
    # create a grouping variable to separate stat_smoothers based on original and one-to-one data 
    df3$grp <- as.factor(rep(1:2, each = nrow(df)))
    
    # plot
    # use original data for points
    # use 'double data' for abline and one-to-one line, set colours by group
    ggplot(df, aes(x = x, y = y)) +
      geom_point(size = 3) +
      facet_wrap(~ type) +
      stat_smooth(data = df3, aes(colour = grp), method = "lm", se = FALSE, size = 1) +
      scale_colour_manual(values = c("red","blue"),
                          labels = c("abline", "one-to-one"),
                          name = "") +
      theme(legend.position = "top")
    
    # If you rather want to stack the two keys in the legend you can add:
    # guide = guide_legend(direction = "vertical")
    #...as argument in scale_colour_manual
    

    请注意,此解决方案不会将一对一的线外推到您的数据范围之外,原始geom_abline 似乎就是这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2019-09-17
      • 2020-12-02
      相关资源
      最近更新 更多