How to put two separate functions on same graph ggplot2

I would like to plot these two functions on the same graph, but for some reason there is no simple way to do so:

ggplot(df1, aes(x=Rate,y=Damage)) +
  geom_smooth(method="auto", se=FALSE) +
  coord_cartesian(xlim=c(0,1000), ylim=c(0, 100)) +
  ggtitle("", subtitle="PPS post-emergence") +
  theme_bw() +
  scale_y_continuous(breaks=seq(0, 100, 20),) +
  xlab("Rate (mg/Ha)") +
  ylab("")

ggplot(x1, aes(x=R, y=V))+
  geom_smooth(method="auto", col="firebrick", se=FALSE) +
  coord_cartesian(xlim=c(0,1000), ylim=c(0, 100)) +
  ggtitle("", subtitle="PPS post-emergence") +
  theme_bw() +
  scale_y_continuous(breaks=seq(0, 100, 20),) +
  xlab("Rate (mg/Ha)") +
  ylab("")

Upvotes: 0

Views: 46

Answers (1)

bobbel
bobbel

Reputation: 2031

Here's an example with simulated data on how to do it:

# generate data
df1 <- data.frame(Rate = rnorm(10, 500, 100), 
                  Damage = rnorm(10, 50, 15))
x1 <- data.frame(R = rnorm(20, 550, 50), 
                 V = rnorm(20, 35, 10))

# plot
ggplot(df1, aes(x = Rate, y = Damage)) +
  geom_smooth(method = "auto", se = FALSE) +
  geom_smooth(data = x1, mapping = aes(x = R, y = V), method = "auto", col = "firebrick", se = FALSE) +
  coord_cartesian(xlim = c(0,1000), ylim = c(0, 100)) +
  ggtitle("", subtitle = "PPS post-emergence") +
  theme_bw() +
  scale_y_continuous(breaks = seq(0, 100, 20),) +
  xlab("Rate (mg/Ha)") +
  ylab("")

The key is to specify new data and mapping arguments in the second geom_smooth statement.

Upvotes: 1

Related Questions