Ras*_*lam 1 r ggplot2 geom-text
我有一个在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))
Run Code Online (Sandbox Code Playgroud)
我想在每个象限中打印百分比值的标签。我当前的代码是:
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)
Run Code Online (Sandbox Code Playgroud)
预期的输出(例如,我显示了类型A和类型B的百分比,我想绘制所有类型和类型的百分比值): 
任何建议都很好。谢谢!
您可能需要计算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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |