Referencing piped dataset in ggplot layers for subsetting

我怕爱的太早我们不能终老 提交于 2019-12-10 11:14:30

问题


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")

回答1:


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")


来源:https://stackoverflow.com/questions/44823676/referencing-piped-dataset-in-ggplot-layers-for-subsetting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!