如何删除每个刻面图上geom_text生成的重复标​​签?

时间:2016-08-18 09:16:08

标签: r ggplot2 facet

我需要生成一个刻面图,显示沿时间轴的事务。另外,我想在所有方面用垂直线标记某些时间戳。

我设法生成了如下图所示的图,它以漂亮的方式显示标签/标记(v4.6.3,v5.0.3,v5.2.3)。然而,它将它们绘制在每个方面,我想避免;更糟糕的是,标签与上面的方面重叠。

Facetted ggplot2 plot with duplicate labels.

我试图使用geom_label解决这个问题,但这只会导致一系列不同的问题(例如没有45度角)。

如何删除除最顶层以外的所有标签?

请在下面找到一个代码段,该代码段应该允许用户重现该情节。

if (!require("pacman")) install.packages("pacman")
library("pacman")
pacman::p_load(plyr, reshape2, ggplot2, lubridate, stringr, grid, gridExtra)


df <- structure(list(instantId = structure(c(1184065080, 1184065080,
1184065082, 1184065080, 1184065084, 1184065084), class = c("POSIXct",
"POSIXt"), tzone = "UTC"), layerId = c("application", "application",
"application", "infrastructure", "infrastructure", "infrastructure")), .Names = c("instantId",
"layerId"), row.names = c(NA, 6L), class = "data.frame")

dfMarkers <- structure(list(version = c("v4.6.3", "v5.0.3", "v5.2.3"), releaseDate = structure(c(1184065081,
1184065083, 1184065085), class = c("POSIXct", "POSIXt"
), tzone = "UTC")), .Names = c("version", "releaseDate"), row.names = c(NA,
3L), class = "data.frame")


RenderTransEvo <- function(df, dfMarkers, boCumulative = FALSE) {
    df <- plyr::count(df, vars = c("layerId","instantId"))
    p <- ggplot(df, aes(instantId)) +
        scale_x_datetime(expand = c(0.0, 0)) +
        theme(plot.margin = unit(c(1,0.1,0.1,0.1),"cm"),
              panel.grid.major.y = element_blank(),
              panel.grid.minor = element_blank(),
              axis.title = element_blank(),
              axis.text.x = element_text(angle = 45, hjust = 1))

         p <- p + geom_area(aes(y = freq)) + facet_grid(layerId ~ ., scales = "free_y", space = "free_y")

        p <- p + geom_vline(color = "blue",
                            xintercept = as.numeric(dfMarkers$releaseDate),
                            linetype = 2,
                            size = 0.25) +
                  geom_text(data = dfMarkers,
                            mapping = aes(x = releaseDate, y = Inf, label = paste0(" ", version)),
                            check_overlap = TRUE,
                            size = 3, angle = 45, vjust = 0, hjust = 0)

  gt <- ggplot_gtable(ggplot_build(p))
  gt$layout$clip[gt$layout$name == "panel"] <- "off"
  grid.draw(gt)
}
RenderTransEvo(df,dfMarkers)

1 个答案:

答案 0 :(得分:3)

如果您将layerId变量添加到dfMarkers,则只会在相应的构面上绘制标签。

dfMarkers$layerId <- "application"

enter image description here