onhalu
onhalu

Reputation: 745

Two ggplot with subset in pipe

I would like to plot two lines in one plot (both has the same axis), but one of the line is subset values from data frame.

I tries this

DF%>% ggplot(subset(., Cars == "A"), aes(Dates, sold_A)) +geom_line()+ ggplot(., (Dates, sold_ALL))

but this error occurred

 object '.' not found

Upvotes: 1

Views: 723

Answers (3)

Allan Cameron
Allan Cameron

Reputation: 173888

I think you are misunderstanding how ggplot works. If we are attempting to do it your way, we could do:

DF %>% {ggplot(subset(., Cars == "A"), aes(Dates, sold_A)) +
        geom_line(colour = "red") +
        geom_line(data = subset(., Cars == "B"), colour = "blue") +
        lims(y = c(0, 60))}

enter image description here

But it would be easier and better to map the variable Cars to the colour aesthetic, so your plot would be as simple as:

DF %>% ggplot(aes(Dates, sold_A, color = Cars)) + geom_line() + lims(y = c(0, 60))

enter image description here

Note that as well as being simpler code, we get the legend for free.


Data

Obviously, we didn't have your data for this question, but here is a constructed data set with the same name and same column variables:

set.seed(1)

Dates  <- rep(seq(as.Date("2020-01-01"), by = "day", length = 20), 2)
Cars   <- rep(c("A", "B"), each = 20)
sold_A <- rpois(40, rep(c(20, 40), each = 20))

DF <- data.frame(Dates, Cars, sold_A)

Upvotes: 2

Eric Krantz
Eric Krantz

Reputation: 2199

(1) You can't add a ggplot object to a ggplot object:

(2) Try taking the subset out of the call to ggplot.

DF %>% 
    subset(Cars == "A") %>% 
    ggplot(aes(Dates, sold_A)) +
    geom_line() +
    geom_line(data = DF, aes(Dates, sold_ALL))

Upvotes: 2

Duck
Duck

Reputation: 39605

If you want only one plot, you would need to remove ggplot(., aes(Dates, sold_ALL)) and wrap directly into a structure like geom_line(data=., aes(Dates, sold_ALL)). Then, use the sage advice from @MrFlick. Here an example using iris data:

library(ggplot2)
library(dplyr)
#Example
iris %>% 
  {ggplot(subset(., Species == "setosa"), aes(Sepal.Length, Sepal.Width)) +
      geom_point()+
      geom_point(data=.,aes(Petal.Length, Petal.Width),color='blue')}

Output:

enter image description here

The ggplot(., aes(Dates, sold_ALL)) is creating a new canvas and the new plot.

Upvotes: 1

Related Questions