上述答案从今天开始有效;但是,它们会发出警告,不鼓励在element_text() 内使用ifelse 的建议方法。 element_text() 中的矢量化未在 ggplot2 中记录的原因是因为它不受支持的功能(由于机会而起作用)。请参阅讨论此特定问题的 GitHub 上的以下issue。
上面提供的答案将导致以下警告:
# Warning message:
# Vectorized input to `element_text()` is not officially supported.
# Results may be unexpected or may change in future versions of ggplot2.
以下代码说明了这一点(使用 SlowLearner 提供的稍微更新的示例 - 原始数据不可用)并显示了我的解决方案,该解决方案支持使用 ggtext 包和 element_markdown() 进行矢量化。
library(ggplot2); packageVersion("ggplot2")
# ‘3.3.0’
library(ggtext); packageVersion("ggtext") #; install.packages("ggtext") # https://github.com/wilkelab/ggtext
# ‘0.1.0’
set.seed(1234)
df <- data.frame(state = paste("State_", LETTERS, sep = ""),
margin = runif(26, -50, 50),
swing = rep(c("no", "yes", "no"), times = c(10, 6, 10)))
mycolours <- c("yes" = "red", "no" = "black")
ggplot(data = df, aes(x = margin, y = state)) +
geom_point(size = 5, aes(colour = swing)) +
scale_color_manual("Swing", values = mycolours) +
theme(
# The following line uses vectorisation (such as rep or ifelse).
# This is not officially supported. Works by a chance and gives impression of a feature.
axis.text.y = element_text(colour = rep(c("black", "red", "black"), times = c(10, 6, 10)))
)
# Throws the following warning:
# Warning message:
# Vectorized input to `element_text()` is not officially supported.
# Results may be unexpected or may change in future versions of ggplot2.
# The following code uses ggtext method # element_markdown(),
# This is how this question should be solved because the vectorisation method may not work in the future inside element_text().
ggplot(data = df, aes(x = margin, y = state)) +
geom_point(size = 5, aes(colour = swing)) +
scale_color_manual("Swing", values = mycolours) +
theme(axis.text.y = element_markdown(colour = rep(c("black", "red", "black"), times = c(10, 6, 10))))
# No warning occurs. This will also correctly calculate other aesthetic such as size.