代码之家  ›  专栏  ›  技术社区  ›  Ben G

如何使用匹配的手动色标创建geom_文本和geom_点?[关闭]

  •  0
  • Ben G  · 技术社区  · 8 年前

    我想创建一个我的标签(来自 geom_text )匹配我使用的手动色阶。下面是一个使用iris数据集的示例。当我输入以下代码时,会出现此错误:

    library(tidyverse)
    
    labels <- tibble(
               Species = c("setosa", "veriscolor", "virginica"),
               Sepal.Length = c(4.3, 5.5, 7), 
               Sepal.Width = c(3.5, 2.3, 3.7))
    
    ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
      geom_point(aes(color = Species)) +
      geom_text(data = labels, 
                aes(x = Sepal.Length, 
                    y = Sepal.Width, label = Species, color = Species),
                inherit.aes = F) +
      scale_color_manual(values = c("gray", "purple", "orange")    
    
    Error: Insufficient values in manual scale. 4 needed but only 3 provided.
    

    我已经看到这与未使用的因子水平有关,但我似乎无法在这里应用它们的解决方案。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Carlos Eduardo Lagosta    8 年前

    错误不是在ggTrm中,而是在您的标签数据帧中:

    labels <-
      data.frame(
        Species = levels(iris$Species),
        Sepal.Length = c(4.3, 5.5, 7), 
        Sepal.Width = c(3.5, 2.3, 3.7) )
    

    还可以在全局aes中指定颜色以简化代码。以及跟随 Gregor 注释,您不需要在geom_文本中指定x和y,因为它也在全局美学中。

    ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
      geom_point() +
      geom_text(data = labels, aes(label = Species)) +
      scale_color_manual(values = c("gray", "purple", "orange"))
    

    enter image description here

    推荐文章