[英]How to converge two plots into one plot (ggplot2)?
我有两个具有不同x轴但相同y轴的图。 每个x轴的顺序必须保持这种方式。 我想通过在底部放置一个x轴并在顶部放置一个x轴来将两个图收敛为一个。
plot1 <- ggplot(df1, aes(x = Target1, y = RT1)) + geom_point() + geom_line(aes(group = 1))
plot2 <- ggplot(df2, aes(x = Target2, y = RT2)) + geom_point() + geom_line(aes(group = 1))
我如何获得想要的情节?
一种方法是使用sec_axis()。 在这里,我创建了两个数据框。 y轴(RT1和RT2)都在同一比例尺上。 Target1和Target2具有不同的比例。
df1 <- data.frame(Target1 = c(1,2,3), RT1 = c(1,2,3))
df2 <- data.frame(Target2 = c(20,30,40), RT2 = c(3,4,5))
为了演示效果,我对df1使用散点图,对df2使用线图。 我还将Target2除以10,以使x变量更接近且更易于比较。
ggplot() +
geom_point(data = df1, mapping = aes(Target1, RT1)) +
geom_line(data = df2, mapping = aes(Target2/10, RT2)) +
scale_x_continuous("Target 1", sec.axis = sec_axis(~.*10, name = "Target 2"))
或者,如果您不想转售x轴,则可以改用dup_axis()。
ggplot() +
geom_point(data = df1, mapping = aes(Target1, RT1)) +
geom_line(data = df2, mapping = aes(Target2, RT2)) +
scale_x_continuous("Target 1", sec.axis = dup_axis(name = "Target 2"))
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.