我有一个数据框,在5种中每种都有10个值,有2种类型。
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)
预期输出(例如,我显示了类型a的A类和B类的百分比,我想绘制所有种类和类型的百分比值):
任何建议都会很棒。谢谢!
答案 0 :(得分:4)
你可能需要计算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))