2017-08-24 37 views
0

我有三個變量(x,y1,y2),y1和y2具有不同比例。請幫助我如何在ggplot2中進行繪圖,x軸分別爲x,y軸和y軸分別爲y軸和y軸。數據如下所示。使用ggplot2在單個圖上繪製具有不同比例的2個y軸

x   y1   y2 
2017  0.2555  655 
2018  0.461926745 566 
2019  0.594491867 363 
2020  0.679623819 233 
2021  0.734294679 140 
+1

你看過這些相似的文章,[1](https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-和另一個y軸在右邊?noredirect = 1&lq = 1),[2](https://stackoverflow.com/questions/6142944/how-can-i-plot-with-2-different -y軸)? – Ashish

+0

你有看過[解決方案](https://stackoverflow.com/a/45855454/4836511)嗎? – Prradep

回答

0

你可以這樣做:

#Reading the data you have provided 
df <- read.table(text = "x   y1   y2 
2017  0.2555  655 
2018  0.461926745 566 
2019  0.594491867 363 
2020  0.679623819 233 
2021  0.734294679 140", header=T) 

# Loading required packages 
library(ggplot2) 
library(gtable) 
library(grid) 

據我所知,沒有任何可用的函數,它產生一個很好的陰謀與雙軸。首先通過分別創建兩個圖開始:

grid.newpage() 

# creating two separate plots 
plot1 <- ggplot(df, aes(x, y1)) + geom_line(colour = "blue") + theme_bw() 
plot2 <- ggplot(df, aes(x, y2)) + geom_line(colour = "red") + theme_bw() 

# extract gtables for each plot 
gtable1 <- ggplot_gtable(ggplot_build(plot1)) 
gtable2 <- ggplot_gtable(ggplot_build(plot2)) 

調整兩個圖重疊在另一個上,然後調整軸。

# overlap the panel of second plot on the first plot 
pp <- c(subset(gtable1$layout, name == "panel", se = t:r)) 
gtable <- gtable_add_grob(gtable1, gtable2$grobs[[which(gtable2$layout$name == "panel")]], 
          pp$t, pp$l, pp$b, pp$l) 

# axis tweaks 
ia <- which(gtable2$layout$name == "axis-l") 
ga <- gtable2$grobs[[ia]] 
ax <- ga$children[[2]] 
ax$widths <- rev(ax$widths) 
ax$grobs <- rev(ax$grobs) 
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm") 
gtable <- gtable_add_cols(gtable, gtable2$widths[gtable2$layout[ia, ]$l], 
          length(gtable$widths) - 1) 
gtable <- gtable_add_grob(gtable, ax, pp$t, length(gtable$widths) - 1, pp$b) 

# drawing the plot with two y-axis 
grid.draw(gtable) 

enter image description here

使用哈德利的想法,我想在Github的問題。一旦找到它,將更新鏈接。

相關問題