簡體   English   中英

如何將兩個圖收斂為一個圖(ggplot2)?

[英]How to converge two plots into one plot (ggplot2)?

我有兩個具有不同x軸但相同y軸的圖。 每個x軸的順序必須保持這種方式。 我想通過在底部放置一個x軸並在頂部放置一個x軸來將兩個圖收斂為一個。

情節1情節2

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

情節1

或者,如果您不想轉售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"))

劇情2

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM