0

I have three variable(years,land,water). I found some code related to two line graph. Is it possible that contain x-axis=year; y-axis=land(line grap) and y-axis(2nd)=water(bar plot)? please help i tried this code

require(plyr)
require(ggplot2)
require(scales)
require(grid)
require(gtable)

grid.newpage()

years<-c("1973","1989","1995","2000","2005","2010","2015")
water<-c(831.96,3033.45,13561.83,11547.27,27161.73,40056.48,35606.16)
land<-
c(219218.4,220326.21,206291.16,206615.43,194822.73,182767.68,187368.03)
df<-data.frame(years=years,water=water,land=land)
print(df,row.names=FALSE)

# two plots
p1 <- ggplot(df, aes(years,water,group = 1 )) + geom_line(colour = "blue") + 
theme_bw()
p2 <- ggplot(df, aes(years,land,group = 2)) + geom_line(colour = "red") + 
theme_bw() %+replace% 
theme(panel.background = element_rect(fill = NA))

# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))

# overlap the panel of 2nd plot on that of 1st plot
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, 
pp$l, pp$b, pp$l)

# axis tweaks
ia <- which(g2$layout$name == "axis-l")
ga <- g2$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")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

# draw it
grid.draw(g)

enter image description here

d.b
  • 32,245
  • 6
  • 36
  • 77
sajib
  • 3
  • 3
  • 1
    Possible duplicate of [Plot with 2 y axes, one y axis on the left, and another y axis on the right](https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-another-y-axis-on-the-right) Hadley Wickham says he intended for this to not be possible. – G5W Jul 21 '17 at 19:13
  • ok sir thank you :) – sajib Jul 21 '17 at 19:31

1 Answers1

0

I think, in general, having two y-axes in one plot is discouraged. It's probably not very easy to do so in ggplot2. It maybe possible using twoord.plot of plotrix package. Here is an example.

library(plotrix)
twoord.plot(lx = as.numeric(df$years), ly = df$water,
            rx = as.numeric(df$years), ry = df$land,
            type = c("h", "b"), lwd = c(6, 1), lend = "butt",
            rcol = "red", xlab = "YEARS",
            ylab = "WATER", rylab = "LAND")

Because the twoord.plot is written using base R, you can modify the twoord.plot function to your liking. Read more at ?twoord.plot and ?plot

d.b
  • 32,245
  • 6
  • 36
  • 77