【问题标题】:Wrong legend in ggplot outputggplot 输出中的错误图例
【发布时间】:2020-08-17 22:53:12
【问题描述】:

这段代码的输出给出了一个分布和两条垂直线,一条红色和一条蓝色。但在传说中,蓝线标记为“红色”,反之亦然。可能是什么原因? Distribution and 2 vertical lines

variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
hist(variances)
v_theo <- 45 ## need to define v_theo
g <- ggplot(data.frame(x=variances), aes(x = x)) 
g <- g + geom_density(alpha=0.2,size=1,fill="red")
g <- g + geom_vline(aes(xintercept = mean(variances),color="red"), size=1) 
g <- g + geom_vline(aes(xintercept = (v_theo),color="blue"), size=1) 
g

【问题讨论】:

    标签: r ggplot2 geom-vline


    【解决方案1】:
    library(ggplot2)
    variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
    hist(variances)
    v_theo <- 45
    
    
    g <- ggplot(data.frame(x=variances), aes(x = x)) 
    g <- g + geom_density(alpha=0.2,size=1,fill="red")
    g <- g + geom_vline(aes(xintercept = v_theo, color="blue"), size=1) 
    g
    

    g <- ggplot(data.frame(x=variances), aes(x = x)) 
    g <- g + geom_density(alpha=0.2,size=1,fill="red")
    g <- g + geom_vline(aes(xintercept = mean(variances),color="mean"), size=1) 
    g <- g + geom_vline(aes(xintercept = v_theo,color="v_theo"), size=1) +
      scale_color_manual(name = "Legend name", values = c(mean = "red", v_theo = "blue"))
    g
    

    也见这里: Add legend to geom_vline

    【讨论】:

      【解决方案2】:

      这是因为颜色是由aes 函数映射的。如果您想手动映射它们,您可以像这样将它们从aes 中取出

      variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
      hist(variances)
      g <- ggplot(data.frame(x=variances), aes(x = x)) 
      g <- g + geom_density(alpha=0.2,size=1,fill="red")
      g <- g + geom_vline(aes(xintercept = mean(variances)), color="red", size=1) 
      g <- g + geom_vline(aes(xintercept = (v_theo)), color="blue", size=1) 
      g
      

      你会因为这样做而失去传奇。如果你想要图例,你可以使用scale_color_manual 来固定颜色的顺序。

      variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
      hist(variances)
      g <- ggplot(data.frame(x=variances), aes(x = x)) 
      g <- g + geom_density(alpha=0.2,size=1,fill="red")
      g <- g + geom_vline(aes(xintercept = mean(variances),color="red"), size=1) 
      g <- g + geom_vline(aes(xintercept = (v_theo),color="blue"), size=1) 
      g <- g + scale_color_manual(values = c("blue", "red"))
      g
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-29
        • 2019-09-04
        • 1970-01-01
        • 1970-01-01
        • 2014-06-19
        • 1970-01-01
        • 2015-10-16
        • 1970-01-01
        相关资源
        最近更新 更多