gpt4 book ai didi

r - 将 ggplot 文本放置在每个角的 facet 中

转载 作者:行者123 更新时间:2023-12-02 00:44:11 27 4
gpt4 key购买 nike

我有一个数据框,其中 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)

当前输出:enter image description here

预期输出(例如,我显示了 A 类和 A 类 B 的百分比,我想绘制所有种类和类型的百分比值):enter image description here

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

最佳答案

你可能需要计算 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))

关于r - 将 ggplot 文本放置在每个角的 facet 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44857394/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com