r - 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?
解决方案
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)
推荐阅读
- python - 如何在power bi中将表格传递给熊猫?
- c# - 使用动态“AutomationID”和没有“名称”属性的 WPF 自动化问题 - C#
- intellij-idea - 运行 JAR - 错误:无法找到或加载主类
- javascript - How do you apply the same javascript code to multiple questions in Qualtrics survey?
- php - 为什么不能在同一行中解码和反序列化?(像这个例子)
- c# - 在学校学习代码目前正在做我的一项练习,但似乎无法解决这个问题
- python - 在所有子图中生成相同的图
- ios - 如何在 UIView 中缩放 CGPoints 和重新缩放
- jobs - Linux 中是否有像 IBM 大型机的 JES 队列那样的自动批处理作业触发工具?
- laravel - 从集合 laravel 中获取相关表的对象