我正在尝试格式化轴文本以反映用于填充下图中的几何图形的相同组。颜色方案是为 aes() 中的 fill 参数选取的,导致 a 和 b、c 之间的颜色不同。然而,element_text() 中使用的 ifelse 语句不会产生正确的颜色格式。
library(ggplot2)
# Make some data (emulating melted format)
df <- cbind.data.frame(c('a', 'a', 'a', 'b', 'c'),
c(5, 5, 5, 15, 45),
c(1, 1, 1, 0, 0))
names(df) <- c('variable', 'value', 'col')
# Conditional statement to be used in plot
con <- ifelse(df$col == 1, 'red', 'green')
# Call to the plot included below
ggplot(df, aes(x = variable, y = value)) +
geom_bar(stat = "identity", aes(fill = col)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = con))
Run Code Online (Sandbox Code Playgroud)
您的con变量有五个元素,其中前三个是“红色”:
[1] "red" "red" "red" "green" "green"
Run Code Online (Sandbox Code Playgroud)
由于只有三个轴标签,因此theme使用前三个值,从而使所有标签变为红色。con当的长度合适时,我们得到期望的结果:
con <- ifelse(unique(df$variable) == 'a', 'red', 'darkgreen')
Run Code Online (Sandbox Code Playgroud)