Overlay different ggplot2 objects

不羁的心 提交于 2019-12-02 11:50:01

This happens because the surv.plot layer contains mappings for a variable called label which is not included in the data for km.plot. You should be able to get around this by adding your surv.plot data as an argument to the geom rather than ggplot() when you create surv.plot. This way the data needed to draw the layer will "travel with" it.

We can illustrate this with simpler data. Let's first create a plot from data with only a few columns:

library(tidyverse)

df1 <- mtcars %>% 
  select(mpg, wt)

# This represents `km.plot`
(p <- ggplot(df1, aes(wt, mpg)) + geom_point())

Now we can try to add a layer that relies on columns not included in df1 to the previous plot:

df2 <- mtcars %>% 
  select(mpg, wt, cyl)

q1 <- ggplot(df2, aes(wt, mpg)) +
  geom_smooth(aes(color = factor(cyl)), method = "lm")

p + q1$layers[[1]]
#> Error in factor(cyl): object 'cyl' not found

q2 <- ggplot() +
  geom_smooth(data = df2, aes(wt, mpg, color = factor(cyl)), method = "lm")

p + q2$layers[[1]]

Created on 2018-07-23 by the reprex package (v0.2.0.9000).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!