代码之家  ›  专栏  ›  技术社区  ›  Denver Dang

平面图上的单个文本重叠

  •  0
  • Denver Dang  · 技术社区  · 8 年前

    我试图用文本标记方面,但它们在每个方面都重叠,而不是一个接一个地显示。这是我一直在使用的代码:

    ggplot(df) +
        aes(x = xvalues, y = yvalues) +
        geom_point(size = 1, shape = 1) +
        facet_wrap(~ model_f, ncol = 3) +
        geom_text(data = df2, aes(x = 33, y = 2.2, label = test), 
                  parse = TRUE, check_overlap = FALSE)
    

    因此,根据我的数据,我应该有6个图(根据 model_f 我的数据中有一列),我得到了。但是当我尝试使用 geom_text 与数据框一起工作:

    df2 <- data.frame(test = c("one", "two", "three", "four", "five", "six"))
    

    每个方面的绘图都获得了所有字符串,但它们相互重叠。如果我使用 check_overlap = TRUE 函数我只得到每个方面的第一个元素,即“一”。

    如何使文本标签分别显示在每个方面?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Michael Harper    8 年前

    如果创建用于添加标签的数据框,则此数据还必须有一列用于方面数据。以iris数据集为例:

    label_text  <- data.frame(lab=c("Label 1","Label 2","Label 3"),
                              Species = levels(iris$Species))
    

    创建以下数据帧:

          lab    Species
    1 Label 1     setosa
    2 Label 2 versicolor
    3 Label 3  virginica
    

    然后我们可以绘制图表:

    ggplot(iris) +
      aes(x = Sepal.Length, y = Sepal.Width) +
      geom_point(size = 1, shape = 1, aes(col = Species)) +
      facet_wrap(~ Species, ncol = 3) +
      geom_text(data = label_text, x = 6.2, y = Inf, aes(label = lab), vjust = 2)
    

    enter image description here

    要改变标签在绘图上的位置,可以改变标签中的x和y坐标 geom_text 论点

    替代方法

    在绘制图形之前,您可以更改刻面名称,而不是将标签添加到绘图中:

    # First we merge the label data as a column to the full dataset
    df <- merge(iris, label_text, by = "Species")
    
    # Then we create our label name
    df$facet <- paste0(df$Species, "\n (stat = ", df$lab, ")")
    
    # Plot the results
    ggplot(df) +
      aes(x = Sepal.Length, y = Sepal.Width) +
      geom_point(size = 1, shape = 1, aes(col = Species)) +
      facet_wrap(~ facet, ncol = 3) + 
      theme(legend.position = "none")
    

    enter image description here

    我个人更喜欢第二种技术,因为您不必担心手动指定坐标。