2017-07-01 17 views
0

我有一个数据框有10个值在每种5种和有2种类型。ggplot文本在每个角落与facet

df <- data.frame(x2=rnorm(100),y2=rnorm(100), type = c(rep("type a", 50), rep("type b", 50)), kind = rep(LETTERS[1:5],10)) 

我想打印每个象限中百分比值的标签。我当前的代码是:

ggplot(df, aes(x2, y2)) + geom_point() + 
    geom_vline(xintercept = 0) + 
    geom_hline(yintercept = 0) + 
    geom_text(data = df, aes(x2, y2, label = "")) + 
    facet_grid(type~kind) 

电流输出:enter image description here

预期输出(例如我展示实物的比例和类型的B,我要绘制的百分比值对所有种类和类型): enter image description here

任何建议都会很棒。谢谢!

回答

3

你可能需要计算比例外GGPLOT2,

library(dplyr) 
numbers <- df %>% group_by(type,kind) %>% mutate(cases = n()) %>% 
    add_count(x2>0,y2>0) %>% mutate(label=paste(round(n/cases*100),"%"), 
            x = ifelse(`x2 > 0`, Inf, -Inf), 
            y = ifelse(`y2 > 0`, Inf, -Inf), 
            hjust = ifelse(`x2 > 0`, 1, 0), 
            vjust = ifelse(`y2 > 0`, 1, 0)) 

ggplot(df, aes(x2, y2)) + geom_point() + 
    geom_vline(xintercept = 0) + 
    geom_hline(yintercept = 0) + 
    facet_grid(type~kind) + 
    geom_label(data=numbers, aes(label = label, x=x, y=y, vjust=vjust, hjust = hjust)) 
+0

这样一个很好的解决方案。非常感谢@baptiste –

+0

我确定有更好的表格制作方式,但我对xtabs和co,或dplyr不熟悉。 – baptiste