4

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")
mtoto
  • 23,919
  • 4
  • 58
  • 71
Mattias W
  • 105
  • 7
  • The second chunk of the code really works? At least there are some typos (`geom_pont`). And also, what you want to plot is not really clear. Are you mixing bar chart and points? – amatsuo_net Jun 29 '17 at 11:35
  • Yes more generally I can't seem to add layers using subset of data without first saving the data in an object to reference from. The choice of layer is not really important. Thanks for the heads up on the typo, will fix. – Mattias W Jun 29 '17 at 13:08

1 Answers1

3

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")
mtoto
  • 23,919
  • 4
  • 58
  • 71