如何删除 R 图表图例中的重复项?
How to remove repeated items in an R chart legend?
我正在使用 starwars
数据集(dplyr
包),我想制作一个图表,其中自变量是字符的高度,因变量是它们的 body质量。此外,我还想通过颜色来辨别物种:
library(dplyr)
starwars
par(mar = c(5.3, 4.3, 4.3, 8.3), xpd = TRUE)
plot(starwars$mass ~ starwars$height, ylim = c(0, 200),
col = as.factor(starwars$species), bty = "l")
legend("topright", inset = c(-0.2, 0), legend = as.factor(starwars$species),
cex = 0.50, col = as.factor(starwars$species),
ncol = 2, pch = 16)
Figure
请注意,某些物种在图例中重复出现。如何排除这些重复?
仅包含 legend
中的 unique
值:
plot(starwars$mass ~ starwars$height, ylim = c(0, 200),
col = as.factor(starwars$species), bty = "l")
legend("topright", inset = c(-0.2, 0),
legend = as.factor(unique(starwars$species)),
cex = 0.50, col = as.factor(unique(starwars$species)),
ncol = 2, pch = 16)
我正在使用 starwars
数据集(dplyr
包),我想制作一个图表,其中自变量是字符的高度,因变量是它们的 body质量。此外,我还想通过颜色来辨别物种:
library(dplyr)
starwars
par(mar = c(5.3, 4.3, 4.3, 8.3), xpd = TRUE)
plot(starwars$mass ~ starwars$height, ylim = c(0, 200),
col = as.factor(starwars$species), bty = "l")
legend("topright", inset = c(-0.2, 0), legend = as.factor(starwars$species),
cex = 0.50, col = as.factor(starwars$species),
ncol = 2, pch = 16)
Figure
请注意,某些物种在图例中重复出现。如何排除这些重复?
仅包含 legend
中的 unique
值:
plot(starwars$mass ~ starwars$height, ylim = c(0, 200),
col = as.factor(starwars$species), bty = "l")
legend("topright", inset = c(-0.2, 0),
legend = as.factor(unique(starwars$species)),
cex = 0.50, col = as.factor(unique(starwars$species)),
ncol = 2, pch = 16)