gpt4 book ai didi

r - 如何允许函数在表达式()中正常执行?

转载 作者:行者123 更新时间:2023-12-01 12:51:44 25 4
gpt4 key购买 nike

我试图将一些标签部分斜体,但仍有 sum()功能,我不知道该怎么做:

library(ggplot2)
library(reshape2)

iris_mean <- aggregate(iris[,1:4], by=list(Species=iris$Species), FUN=mean)
iris_sd <- aggregate(iris[,1:4], by=list(Species=iris$Species), FUN=sd)
df_mean <- melt(iris_mean, id.vars=c("Species"), variable.name = "Samples", value.name="Values")
df_sd <- melt(iris_sd, id.vars=c("Species"), variable.name = "Samples", value.name="Values")
limits <- aes(ymax = df_mean[,"Values"] + df_sd[,"Values"], ymin=df_mean[,"Values"] - df_sd[,"Values"])
df_mean$Species <- factor(df_mean$Species, levels=unique(df_mean$Species), ordered=TRUE)

ggplot(df_mean, aes(Samples, Values, fill = Species)) +
geom_bar(position="dodge", stat="identity") + coord_flip() +
theme(axis.text.y=element_text(angle=0, hjust=1)) +
theme_minimal() +
theme(
legend.position = "bottom",
plot.margin = unit(c(1,1,.5,0),"cm"),
legend.key.size = unit(.5, "lines"),
axis.text.y = element_text(face = "italic")
) +
scale_x_discrete("",
labels= expression(
paste(italic("I. setosa"), " (n=", sum(iris == "setosa"), ")"),
paste(italic("I. versicolor"), " (n=", sum(iris == "versicolor"), ")"),
paste(italic("I. virginica"), " (n=", sum(iris == "virginica"), ")")))
当前情节:
Current plot
想要的剧情:
Desired plot

最佳答案

只看scale_x_discrete,你就可以做到

scale_x_discrete("", 
labels= c(
bquote(italic("I. setosa")*" (n="*.(sum(iris == "setosa")) * ")"),
bquote(italic("I. versicolor")*" (n="*.(sum(iris == "versicolor")) * ")"),
bquote(italic("I. virginica")*" (n="*.(sum(iris == "virginica")) * ")")))
这里我们使用 bquote()将值“插入”到表达式中。我们使用 .() 来做到这一点 bquote() 内的函数调用在当前环境中计算表达式并将值插入到表达式中。
您可以使用以下命令自动创建这些
x <- c("setosa", "versicolor", "virginica")
xlabels <- lapply(x, function(spec) {
bquote(italic(.(paste("I.", spec)))*" (n="*.(sum(iris == spec)) * ")")
})
然后使用
+ scale_x_discrete("", labels= xlabels)

关于r - 如何允许函数在表达式()中正常执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972358/

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