2017-08-24 3 views
0

J'ai trois variables (x, y1, y2) avec y1 et y2 ayant des échelles différentes. Veuillez m'aider à faire le tracé dans ggplot2 avec x sur l'axe x, y1 et y2 sur l'axe y à gauche et à droite respectivement. Les données sont montrées ci-dessous.Tracer avec 2 axes y avec échelle différente sur un seul graphique en utilisant ggplot2

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

Avez-vous regardé ces messages similaires, [1] (https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left- et-autre-y-axe-sur-le-droit? noredirect = 1 & lq = 1), [2] (https://stackoverflow.com/questions/6142944/how-can-i-plot-with-2-different -y-axes)? – Ashish

+0

Avez-vous regardé la [solution] (https://stackoverflow.com/a/45855454/4836511)? – Prradep

Répondre

0

Vous pouvez faire comme ceci:

#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, il n'y a pas de fonction disponible qui produit un beau terrain avec l'axe double. Tout d'abord en commençant par la création de deux parcelles séparément:

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

Réglage des deux parcelles en faisant se chevaucher sur sur l'autre, puis en ajustant l'axe.

# 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

En utilisant l'idée de Hadley, je pense que sur les questions Github. Mettra à jour le lien, une fois que je l'ai trouvé.