Can I plot 2 data subsets (regression line with confidence interval) in 1 graph?

I've got a dataset with several subset inside it.
Data: x,y,subsetID
I want to plot two of these subsets using regression lines with confidence (and prediction) areas.
However, I want those two (line+area) plots in the same plot. Not next to each other but overlapping (using alpha and color to visually separate them).
Currently I'm using ggplot to create one graph of one subset of data, but I'm at a loss how to plot two inside one graph.

Thx,

Marco

You can specify the data argument for each geom in your ggplot call - consider the following code:

library(ggplot2)

# a built in dataset
first <- pressure

# a slight modification of the first df
second <- data.frame(temperature = first$temperature,
                     pressure = rev(first$pressure))

ggplot(mapping = aes(x = temperature, y = pressure)) +
  geom_line(data = first, color = "red") +
  geom_line(data = second, color = "blue")

The code is intentionally simplistic, but you can see that both lines are using different underlying data frames - red is on the first, blue on the second.

As the structure of both data frames remains the same I could get away with declaring the aes() only once in the "root" ggplot call; if this were not the case you could always declare the aesthetics for each geom separately.

Note that when using separate data arguments you may need to tweak the range of your axes a bit; this will depend on your actual use case.

example of linear model over 3 sets of species in iris data

library(ggplot2)

ggplot(data= iris , 
       mapping = aes(x = Petal.Width,
                     y = Petal.Length,
                     color=Species)) +
  geom_smooth(method='lm', formula= y~x) 

Edited::as replied to wrong post.

@assignUser
Thanks all for the quick reply!
I just found out about the AES option of color/linetype. That seems to work fine.
Two questions:
1 - what does the option do in the AES?
2 - how can I control the color,line,alpha etc of each subset plot?

Cheers,

Marco

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

Depending on your use case and format of your data you can either give each geom its own data like @jlacko showed, alternativly you can use the group aesthetic like this:

df <- data.frame(x = 1:100, y = rnorm(100) ,id= sample(1:2,100,replace = T))

ggplot(df,aes(x,y,,color = id, group = id)) + geom_point() + geom_smooth()

You'r welcome! I think these questions are answered best in the ggplot2 Reference:
aes() - aesthetic mappings
geom_smooth() - smooth means
It should be noted that every geom_* has different aes options available, so in doubt check the matching reference for details!