如何在同一个图形ggplot2上放置两个单独的函数

时间:2018-12-12 14:47:55

标签: r ggplot2

我想在同一张图上绘制这两个函数,但是由于某种原因,没有简单的方法可以做到这一点:

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

1 个答案:

答案 0 :(得分:1)

以下是有关如何执行此操作的模拟数据的示例:

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

关键是在第二条data语句中指定新的mappinggeom_smooth参数。