Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing piped dataset in ggplot layers for subsetting

Trying to find a way to reference different parts of the dataset for different ggplot2 geom layers without having to save the dataset first in the global environment.

Ex non working solution.

read_excel("Book1.xlsx",sheet = "Sheet2") %>% 
  ggplot(aes(x,y)) +
  geom_col() +
  geom_point(data=subset($ID == "1"),colour="red")

Above does not seem to work since i am not referencing the piped(magrittr) dataset in a way that R can recognize it. I have searched but the only solutions i could see are based of the one where i first save the dataset in the global environment as such

Ex working solution with saving the dataset first.

df <- read_excel("Book1.xlsx",sheet = "Sheet2")

  ggplot(df,aes(x,y)) +
  geom_col() +
  geom_point(data=subset(df,ID == "1"),colour="red")
like image 852
Mattias W Avatar asked Aug 31 '25 18:08

Mattias W


1 Answers

You could try using dplyr:

library(dplyr)
library(ggplot2)

read_excel("Book1.xlsx",sheet = "Sheet2") %>% 
  ggplot(aes(x, y)) +
  geom_col() +
  geom_point(data = . %>% filter(ID == "1"), colour = "red")
like image 139
mtoto Avatar answered Sep 02 '25 09:09

mtoto