【问题标题】:How to remove repeated items in an R chart legend?如何删除 R 图表图例中的重复项?
【发布时间】:2021-08-03 09:47:49
【问题描述】:

我正在使用starwars 数据集(dplyr 包),我想制作一个图表,其中自变量是字符的高度,因变量是他们的体重。此外,我还想通过颜色来辨别物种:

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

请注意,有些物种在图例中重复出现。如何排除这些重复?

【问题讨论】:

    标签: r database dplyr graphics dataset


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2015-06-08
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多