根据条件在ggplot中分配标签颜色会返回意外(且不正确)的结果

Rek*_*rrr 4 r ggplot2 axis-labels

发生的事情确实很奇怪,如果我尝试根据满足的条件分配轴标签的颜色,则返回的图的轴标签的颜色与标准不匹配。

例如

 p <- ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + 
  geom_boxplot() 
p +  theme(axis.text.x = element_text(color = ifelse(mtcars$cyl==4, "red", "black"), angle = 90, hjust = 1))
Run Code Online (Sandbox Code Playgroud)

返回箱形图,其中“ 8”标记为红色,“ 4”和“ 6”为黑色。但是,如果我在任何情况下都设置了不正确的条件,例如:

p <- ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + 
  geom_boxplot() 
p +  theme(axis.text.x = element_text(color = ifelse(mtcars$cyl=="something", "red", "black"), angle = 90, hjust = 1))
Run Code Online (Sandbox Code Playgroud)

所有标签均为黑色。

如果我选择一个都满足的条件,它们都是红色的,例如:

p <- ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + 
  geom_boxplot() 
p +  theme(axis.text.x = element_text(color = ifelse(mtcars$cyl < 100, "red", "black"), angle = 90, hjust = 1))
Run Code Online (Sandbox Code Playgroud)

但是,只要其中一些符合条件,我都会得到随机结果。

p <- ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + 
  geom_boxplot() 
p +  theme(axis.text.x = element_text(color = ifelse(mtcars$cyl < 5, "red", "black"), angle = 90, hjust = 1))
Run Code Online (Sandbox Code Playgroud)

仅返回8作为红色,并且

p <- ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + 
  geom_boxplot() 
p +  theme(axis.text.x = element_text(color = ifelse(mtcars$cyl < 7, "red", "black"), angle = 90, hjust = 1))
Run Code Online (Sandbox Code Playgroud)

将它们全部返回为红色。

有人知道发生了什么吗?任何帮助将非常感激。

And*_*rie 5

请注意,您的输入数据包含许多元素,而小数位仅包含三个元素,与您的数据级别相对应。

因此,您必须传递一个scale_x_discrete长度为3 的向量,而不是数据的长度。

breaks <- levels(as.factor(mtcars$cyl))
colours <- ifelse(breaks == 4, "red", "blue")

ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + 
  geom_boxplot() +
  scale_x_discrete("Cyl", breaks = breaks) +
  theme(axis.text.x = element_text(color = colours, size = 16))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明