将注释放在ggplot上,在y轴上为TRUE和FALSE

时间:2017-10-19 13:23:02

标签: r ggplot2

下面的代码完成了我需要的两个简化图,但需要一个幻数用于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)

Simplified T/F plot Simplified 0/1 plot

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

2 个答案:

答案 0 :(得分:1)

功能getYplace可以满足您的需求。它检查vector是否为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))

答案 1 :(得分:1)

我认为确定注释的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))))