Subsetting ggplot data

I'm creating a series of using various time periods for a series of stock prices. For each stock, I create a graph for 1, 2, 3, 5, 10, and 15 years.

The code is something like

graphOutput <- data %>% ggplot() + geom_line(....) + geom_text(...)

How can I create the graph for 15 years, and then subset it for 10, 5, 3, 2, and 1 years and save elapsed and computational time? I've tried

graphOutput %>% filter(data$Date > "2022-06-01")

but I get the error message

*Error in UseMethod("filter") : *

  • no applicable method for 'filter' applied to an object of class "c('gg', 'ggplot')"*

Any suggestions?

I think we need to see the actual code and data.

See FAQ: How to do a minimal reproducible example ( reprex ) for beginners for some suggestions.

says it all—a ggplot result is not the sort of object that can be given as an argument to filter() or dplyr::filter() even though the data, which can be, is deeply embedded in the plot object.

Start with data, rename it to Data or some other name that is not a built-in. Subset that, create separate graphs and present with {patchwork} or a similar package.

1 Like

Please try to generate a list from the ggplot and in the list consider the data list and subset that and use it as shown in the example below

library(tidyCDISC)
data('advs', package='tidyCDISC')

advs <- advs %>% rename_all(tolower) %>% filter(anl01fl=='Y' & paramcd=='DIABP')

g <- ggplot(advs, aes(x=ady,y=aval, group=atpt)) + 
  geom_line(aes(color=atpt))

#if i want to subset the ggplot for a particular subject then i have to write the below code

g$data <- g$data %>% filter(sex=='M' & usubjid=='01-701-1033')

#just call the g and graph for only one subject will be generated 

g

I did as you suggested and it works!

Thanks.

could you please share the actual code you tried to help you

could you please mark it as a solution so it will be helpful for others with similar issue.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.