我正在运行这本书的示例“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/