gpt4 book ai didi

r - 如何使用 bquote() 在 scale_x_discrete() 内的 ggplot2 中动态创建标签?

转载 作者:行者123 更新时间:2023-12-04 10:52:18 25 4
gpt4 key购买 nike

目前,我必须对 scale_x_discrete() 内的标签进行硬编码。但我需要动态创建它们的一个子集,并将它们按降序排列,并在具有静态位置的 y 轴底部添加附加标签。

library(dplyr)
library(ggplot2)
library(scales)

set.seed(1)

samp <- data.frame(Names = sample(paste0("Sample_", 1:5), 90, replace = TRUE),
Mode = rep(c("UN", "CN", "CF"), 150))

ggplot(samp, aes(x=Names)) +
geom_bar(aes(fill=Mode), position="fill", width = .5) +
scale_fill_manual(values = c("#a0de6f","tan1","#DAEBFF")) +
scale_y_continuous(label=percent, expand = c(0,0)) +
coord_flip() +
labs(fill="",
x="",
y="") +
theme_minimal() +
theme(
legend.position = "bottom",
plot.margin = unit(c(1,1,.5,0),"cm"),
legend.key.size = unit(.5, "lines")
) +
guides(fill = guide_legend(reverse = TRUE)) +
scale_x_discrete("",
labels= c(
bquote("Sample_5" * " (n = " * .(sum(samp$Names == "Sample_5")) * ")"),
bquote(italic("Sample_1") * " (n = " * .(sum(samp$Names == "Sample_1")) * ")"),
bquote(italic("Sample_3") * " (n = " * .(sum(samp$Names == "Sample_3")) * ")"),
bquote(italic("Sample_4") * " (n = " * .(sum(samp$Names == "Sample_4")) * ")"),
bquote(italic("Sample_2") * " (n = " * .(sum(samp$Names == "Sample_2")) * ")")))

这一点:
  scale_x_discrete("", 
labels= c(
bquote("Sample_5" * " (n = " * .(sum(samp$Names == "Sample_5")) * ")"),
bquote(italic("Sample_1") * " (n = " * .(sum(samp$Names == "Sample_1")) * ")"),
bquote(italic("Sample_3") * " (n = " * .(sum(samp$Names == "Sample_3")) * ")"),
bquote(italic("Sample_4") * " (n = " * .(sum(samp$Names == "Sample_4")) * ")"),
bquote(italic("Sample_2") * " (n = " * .(sum(samp$Names == "Sample_2")) * ")")))

是我需要动态创建并按计数降序排列的东西,但我真的不知道如何。

它应该是什么样子:

enter image description here

最佳答案

您可以分别为动态部分和静态部分生成标签列表,然后将它们组合起来

excludes <- "Sample_5"
cat_counts <- table(samp$Names) %>% {.[-match(excludes, names(.))]}
my_sorted_labels <- Map(function(label, count) {
bquote(italic(.(label)) * " (n = " * .(count) * ")")
}, names(cat_counts), cat_counts)[order(cat_counts)]
my_sorted_limits <- names(sort(cat_counts))

my_fixed_labels <- Map(function(label, count) {
bquote(.(label) * " (n = " * .(count) * ")")
}, excludes, table(samp$Names)[excludes])

my_labels <- c(my_fixed_labels, my_sorted_labels)
my_limits <- c(excludes, my_sorted_limits)

然后使用它
scale_x_discrete("", limits=my_limits, labels= my_labels)

关于r - 如何使用 bquote() 在 scale_x_discrete() 内的 ggplot2 中动态创建标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51066784/

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