使用ggplot2在单个图上绘制具有不同比例的2 y轴

时间:2017-08-24 07:15:25

标签: r ggplot2 axes

我有三个变量(x,y1,y2),y1和y2具有不同的比例。请帮助我如何在ggplot2中使用x轴上的x,左右y轴上的y1和y2来绘制图。数据如下所示。

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

1 个答案:

答案 0 :(得分: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)

AFAIK,没有可用的功能,可以产生双轴的漂亮情节。首先分别创建两个图:

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

使用Hadley的想法,我想在Github问题上。一旦找到,就会更新链接。

相关问题