【问题标题】:R: ggplot fill one factor in a 2x2 factorial experimentR:ggplot 在 2x2 因子实验中填充一个因子
【发布时间】:2017-07-11 20:06:59
【问题描述】:

我对几种不同的植物物种进行了 2x2 因子实验。我有一段时间正确地策划这一切。

虚拟数据:

Data <- data.frame(
species = rep(letters[1:4], each = 4),
F1 = rep(letters[25:26], times = 8), 
F2 = rep(letters[11:12], each = 2, times = 4),
mean = runif(16, min=0, max=1),
se = (runif(16, min=0, max=1))/10)

我想要 X 轴上的物种名称,以及 4 个单独的点(+ SE 条),每个因素 2 个。一个因素将被填充或为空,另一个将是我到目前为止所得到的:

pd <- position_dodge(0.5)
ggplot(Data, aes(species, mean, fill = factor(F1), shape = factor(F2))) +
geom_point(size = 3, position = pd) +
geom_errorbar(aes(ymin=mean-se, ymax=mean+se), position = pd)

但是,这实际上并没有使因子 1 成为填充或未填充的形状。我已经跟随 mtcars 中的几个例子,我已经很好地工作了。这里出了什么问题?

对于它的价值,颜色工作正常,但我需要填充或空,所以看起来我可能使用错误填充?

【问题讨论】:

  • 只需将fill 更改为colour 即可。这也会给误差线着色。如果你真的想要填充绘图符号,你可以使用+ scale_shape_manual(values=c(21, 24))。
  • 这是 ggplot2 和基本 R 图形中符号形状和线型的好资源:cookbook-r.com/Graphs/Shapes_and_line_types

标签: r ggplot2 colors fill


【解决方案1】:

fill 美学用于填充颜色条。点,是“固体”与否。

我不知道一个步骤的解决方案来构建一个点是否实心或不是一个因素的情节。不过,那里建造这样的地块并不太难。

让我们从构建Data开始

library(ggplot2)

Data <- data.frame(species = rep(letters[1:4], each = 4),
                   F1      = rep(letters[25:26], times = 8), 
                   F2      = rep(letters[11:12], each = 2, times = 4),
                   mean    = runif(16, min=0, max=1),
                   se      = (runif(16, min=0, max=1))/10)

将Data 组合F1 和F2 添加一列。您可以使用interaction() 函数,但我将使用paste(paste0(...) 相当于paste(..., sep = ""))来构建列并将其设置为factor。

Data$F1F2 <- factor(with(Data, paste0("F1 = ", F1, "; F2 = ", F2)))
levels(Data$F1F2)

现在,在ggplot 对象中使用scale_shape_manual 将特定点字符映射到Data$F1F2 的级别。在此示例中,点字符c(1, 2, 16, 17) 对应于非实心圆、非实心三角形、实心圆和实心三角形。

pd <- position_dodge(0.5)
ggplot(Data) +
  aes(species, mean, color = species, shape = F1F2) +
  geom_point(size = 3, position = pd) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), position = pd) +
  scale_shape_manual(name = "Factors",
                     values = c(1, 2, 16, 17))

生成的图形如下。我添加了一种颜色美学来帮助我查看species 的分组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多