r - 为什么我不能在 ifelse() 中使用 element_text()?

标签 r ggplot2

我怎么不能返回 element_text()

> ifelse(TRUE,element_text(size=20),element_text(size=10))
[[1]]
NULL

但我能做到吗?

> element_text(size=20)
List of 8
 $ family    : NULL
 $ face      : NULL
 $ colour    : NULL
 $ size      : num 20
 $ hjust     : NULL
 $ vjust     : NULL
 $ angle     : NULL
 $ lineheight: NULL
 - attr(*, "class")= chr [1:2] "element" "element_text"

最佳答案

您不能以您尝试使用它的方式:

这是我的意思的一个例子:

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + 
    geom_boxplot() + 
    theme(legend.text = element_text(size=ifelse(TRUE, 20, 10)))

这与您正在使用的 if else (ifelse) 有关,它是矢量化的。我想你是在 if(){}else{} 之后:

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + 
    geom_boxplot()+ 
    theme(legend.text = if(TRUE){element_text(size=20)} else {element_text(size=10)})

虽然我真的不会以这种方式格式化它,但将其保留在一行中以便与您的方法进行比较。

问题不在于 ggplot2 而是您对 ifelse 的使用。查看 ?ifelse 和文档说:

 ‘ifelse’ returns a value with the same shape as ‘test’ which is
 filled with elements selected from either ‘yes’ or ‘no’ depending
 on whether the element of ‘test’ is ‘TRUE’ or ‘FALSE’.

在您的问题中,您显示的 element_text(size=10) 的输出与 test 的结构不同。

关于r - 为什么我不能在 ifelse() 中使用 element_text()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13104631/

相关文章:

r - 估计ggplot2中图例占用的绘图百分比

r - 提取 lapply 中列出的数据框名称

r中向量和矩阵之间的行比较

r - 按变量获取包

r - 通过检查所有列的部分文本来过滤行

r - facet_grid ggplot2 中每个方面的scale_x_date

r - 从 R 中的 rpart 对象中提取拆分值

r - 如何使用 XML2 包解析 XML 文件的子路径

r - 如何让geom_text继承主题规范? (ggplot2)

r - ggplot2 时间序列绘图 : how to omit periods when there is no data points?