r - 对使用 [ ] 索引颜色列表感到困惑

标签 r

我正在运行这本书的示例“Beckerman, A. P., & Petchey, O. L. (2012)。R 入门。生物学家简介。牛津,Reino U nido:牛津大学出版社。”

例子是这样的

# plot window 
par(mfrow = c(1,1))
# the plot
plot(EGGS ~ DENSITY, data = limp, pch = 19, cex = 1.5, 
    col = c("Black","Red")[limp$SEASON], 
    xlab = list("Density", cex = 1.2), 
    ylab = list("Eggs Produced", cex = 1.2))
# add a legend 
legend(35,3,legend = c("spring","summer"),  
     col = c("black", "red"), pch = c(19, 19))

但是如果我包含 limp$SEASON R 不会在绘图上打印数据。

这是数据

structure(list(DENSITY = c(8L, 8L, 8L, 8L, 8L, 8L, 15L, 15L, 
15L, 15L, 15L, 15L, 30L, 30L, 30L, 30L, 30L, 30L, 45L, 45L, 45L, 
45L, 45L, 45L), SEASON = c("spring", "spring", "spring", "summer", 
"summer", "summer", "spring", "spring", "spring", "summer", "summer", 
"summer", "spring", "spring", "spring", "summer", "summer", "summer", 
"spring", "spring", "spring", "summer", "summer", "summer"), 
    EGGS = c(2.875, 2.625, 1.75, 2.125, 1.5, 1.875, 2.6, 1.866, 
    2.066, 0.867, 0.933, 1.733, 2.23, 1.466, 1, 1.267, 0.467, 
    0.7, 1.4, 1.022, 1.177, 0.711, 0.356, 0.711), season = structure(c(1L, 
    1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 
    2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("spring", "summer"
    ), class = "factor")), row.names = c(NA, -24L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x55d2263c37f0>)

最佳答案

@DanY 的回答提供了很好的一般背景,但这个例子不起作用的可能具体原因是它只有在 limp$SEASON 时才有效。是一个整数向量或一个因子。在 R 版本 4.0 之前(即编写此示例时),导入数据的默认设置是字符列将自动转换为因子 (stringsAsFactors = TRUE)。这不再是默认值,因此您可能需要指定 limp$SEASON <- factor(limp$SEASON)在尝试绘图代码之前。

关于r - 对使用 [ ] 索引颜色列表感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70278740/

相关文章:

r - 从 R 中两个较大的 data.frame 中的任意两个同名变量中生成 `data.frame`

r - 在 R 中的相关列之间高效交换值

r - 在 R 中没有 lm 对象的情况下计算 Newey-West 标准误差

windows - R 15.2 Windows XP 下的 cppFunction(Rcpp) 错误

r - 当绘图中使用超过 3 种颜色时,图例中的 geom_smooth 着色会产生误导

r - 将文本从多个连接附加到单个文件的最可靠方法是什么

r - 将 float 序列与向量进行比较

python - 拓扑数据分析 - 从哪里开始

r - 在 bool 向量中找到*第一个*最长的 TRUE 序列

r - 向维恩图添加图例