首页 > 解决方案 > remove layers from ggplot chart with particular layers automatically

问题描述

I would like to automatically remove the geom_label layers from a ggplot chart that have a particular label. My code is:

library(ggplot2)
library(gginnards)

df <- data.frame(x=1:100, y=runif(100))

gp <- ggplot(df, aes(x=x, y=y)) +
      geom_point() +
      geom_label(aes(x=20, y=-Inf, label="A"), vjust = -0.2) +
      geom_label(aes(x=40, y=-Inf, label="B"), vjust = -0.2) +
      geom_label(aes(x=60, y=-Inf, label="A"), vjust = -0.2) +
      geom_label(aes(x=80, y=-Inf, label="C"), vjust = -0.2)

print(gp)

I tried:

gp <- delete_layers(gp, match_type = "GeomLabel")

using the gginnards package, but then all geom_labels are removed. In this example I would like to automatically remove only the geom_labels from the ggplot chart that have label "A", for example with something like:

gp <- delete_layers(gp, match_type = "GeomLabel" & label = "A")

Is this possible? How?

标签: rggplot2

解决方案


Here is an answer that solves your specific question about removing the geom_label layers when the label is set to A. You can turn it into a function fairly easily.

The answer makes use of the extract_layers function to grab all the layers and find the corresponding labels for each geom_label layer. I then subset the result to get the indices of the labels when they equal "A". Finally I use the idx parameter (instead of the match_type parameter) of the delete_layers function to remove the target layers by their index.

Note that you cannot use both the match_type and the idx parameters at the same time in the delete_layers function.

library(ggplot2)
library(gginnards)

set.seed(1234)

df <- data.frame(x = 1:100, y = runif(100))

gp <- ggplot(df, aes(x = x, y = y)) +
    geom_point() +
    geom_label(aes(x=20, y=-Inf, label="A"), vjust = -0.2) +
    geom_label(aes(x=40, y=-Inf, label="B"), vjust = -0.2) +
    geom_label(aes(x=60, y=-Inf, label="A"), vjust = -0.2) +
    geom_label(aes(x=80, y=-Inf, label="C"), vjust = -0.2)

print(gp)

# get the geomlabel layers
geom_label_layers <- extract_layers(gp, match_type = "GeomLabel")

# get the labels for each of the geomlabel layers 
labels_vals <- sapply(geom_label_layers, function(x) x$mapping$label)

# get the indices of the labels that equal "A", and then add 1 to them because the first layer is the geom_point() layer and we don't want to remove that
A_labels_idx <- which(labels_vals %in% "A") + 1

# delete the layers using the indices we just found
gp2 <- delete_layers(gp, idx = A_labels_idx)

print(gp2)



推荐阅读