【问题标题】:Place an annotation onto a ggplot with TRUE and FALSE on the y-axis在 y 轴上使用 TRUE 和 FALSE 将注释放置在 ggplot 上
【发布时间】:2017-10-19 13:23:01
【问题描述】:

以下代码可以满足我对两个简化图的需求,但需要一个幻数来表示 y 位置而不是计算(已注释掉)。

df1 <- data.frame(y=c(TRUE,TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,FALSE,FALSE),
                 x=c(1,2,3,4,5,6,7,8,9))
df2 <- data.frame(y=c(1,1,0,1,0,1,0,0,0),
                 x=c(1,2,3,4,5,6,7,8,9))

# yplace <- mean(as.numeric(levels(as.factor(df$y))))
yplace1 <- 1.5
yplace2 <- 0.5

library(ggplot2)
ggplot(data=df1, aes(x=x,y=y)) + geom_point() +
    annotate("text", label="read me", x=mean(df1$x), y=yplace1)
ggplot(data=df2, aes(x=x,y=y)) + geom_point() +
    annotate("text", label="read me", x=mean(df2$x), y=yplace2)

我正在尝试编写一个通用函数,它将注释放置在任何二项式散点图的中心。注释掉的 yplace 分配是我想到的最接近的东西,但它导致 TRUE/FALSE 分布的 NA 。如果 y 向量都是 1 和 0,并且所有 TRUE 和 FALSE 都返回 1.5,我是否可以使用一个函数或计算来返回 0.5?我想不出任何其他常用的二项分布,但处理 y 向量包含两个因子的任何情况都是理想的。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    函数getYplace 做你想做的事。它检查向量是否为 TRUE/FALSE 并返回 1.5 或者如果它是数字则返回两个数字之间的平均值。

    getYplace <- function(Y) {
        if (is.numeric(Y)) {
            res <- mean(unique(Y))
        } else {
            res <- 1.5
        }
        return(res)
    }
    
    library(ggplot2)
    ggplot(df1, aes(x, y)) + 
        geom_point() +
        annotate("text", label = "read me", x = mean(df1$x), y = getYplace(df1$y))
    
    ggplot(df2, aes(x, y)) + 
        geom_point() +
        annotate("text", label = "read me", x = mean(df2$x), y = getYplace(df2$y))
    

    【讨论】:

    • 希望您不要介意,我发现 is.logical() 和 unique() 非常有用,因此我调整了您的条件以涵盖所有情况,而不仅仅是逻辑。
    • @mightypile 哦,我明白了,很乐意提供帮助 :-)
    【解决方案2】:

    我相信,只要它们是数字,确定注释的 y 值就可以使用因子的平均值。如果它们不是数字,因子将被分配计数数字,1,2,3,...

    因此,以下方法可能适用于所有双因子向量,但并没有让我觉得非常优雅,并且计算了两次丑陋的平均值。

    yplace1 = if(is.na(mean(as.numeric(levels(as.factor(df1$y))))))
        1.5
    else
        mean(as.numeric(levels(as.factor(df1$y))))
    

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多