【问题标题】:R - Box Plot Conditional Colors not WorkingR - 箱线图条件颜色不起作用
【发布时间】:2016-07-06 10:27:42
【问题描述】:

我正在尝试有条件地对我的箱形图进行颜色编码,但它并不能始终如一地工作。我希望有人能找出问题所在。如果我能提供帮助,我希望不要使用 ggplot,因为我对 R 很陌生,并且想坚持我所知道的(现在)。

基本上,我正在制作一系列箱形图,其中 9 个箱子中有 2 个需要不同颜色。我无法指定颜色模式,因为两个框的位置在每个图形的 x 轴上都会发生变化。我有一个标有“Control”的列,其值为 0、2 或 4。我希望所有值 Control=0 为 gray80,Control=4 为 gray40,Control=2 为白色。我尝试通过两种方式来实现这一点:

#BoxPlot with Conditional Coloring, ifelse statement
boxplot(Y~X, ylab="y", 
 xlab="x", 
 col=ifelse(Control>=3, "gray40", ifelse(Control<=1, "gray80","white")))

#Colors
colors <- rep("white", length(Control))
colors[Control=4] <- "gray40"
colors[Control=0] <- "gray80"

#BoxPlot with Conditional Coloring, "Colors"
boxplot(Y~X, ylab="y", 
 xlab="x", 
 col=colors)

在所附的箱线图中,只有前两个框应该涂上颜色。谁能告诉我我做错了什么? 1

【问题讨论】:

  • 如果有机会,你能发个reproducible example吗?在那之前,你或许可以试试ifelse(Control == 0, "gray80", ifelse(Control == 2, "white", "gray40"))

标签: r if-statement colors boxplot


【解决方案1】:

这里有两种方法。如果它对您不起作用,那么一个可重现的示例将是可行的方法(请参阅我在您原始问题下的评论)。

xy <- data.frame(setup = rep(c(0, 2, 4), 50), value = rnorm(150))

boxplot(value ~ setup, data = xy)

boxplot(value ~ setup, data = xy, col = ifelse(xy$setup == 0, "gray80", ifelse(xy$setup == 2, "white", "gray40")))

library(ggplot2)

xy$setup <- as.factor(xy$setup)


ggplot(xy, aes(y = value, fill = setup, x = setup)) +
  theme_bw() +
  geom_boxplot() +
  # order of colors is determined by the order of levels of xy$setup
  scale_fill_manual(values = c("gray80", "white", "gray40"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2017-06-19
    • 1970-01-01
    相关资源
    最近更新 更多