2

I'm a rookie in R programming and have been struggling with a 2-y axis plots for some days. Finally, I almost managed to build a chat that the client asked with one exception: both of my 2 lines are of the same color that is not what I wanted.

I used a common script found on the Internet adjusted to my needs. The only thing I can't figure out is how to make lines of different colors and not changing ggplot() function since it produces legends that are combined for a final plot (if we set lines to be of particular color then "guide-box" objects are not a part of grobs of either plots and R returns an error).

So, I would very much appreciate someones help/thoughts on the subject as I want to use the following script to build 3-5 lines plots and need to find a solution right away.

The script:

library(ggplot2)
library(zoo)
library(gtable)
library(grid)

p4.1prod <-ggplot(data = p4_ch2_prod, aes (x = date, y = productivity, colour = productivity)) +
  #Производительность труда, 2013=100
  geom_line(size = 1)+
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_prod$date), to = max(p4_ch2_prod$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(85,105,5), expand = c(0,0), limits = c(85,105)) + #setting the domain of the scale

  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "black"),
        panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .2),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "#EDEDED", size = .2),
        panel.grid.minor = element_blank(),
        panel.background = element_rect(fill = "transparent", colour = NA),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1prod 


p4.1ret <- ggplot(data = p4_ch2_ret, aes (x = date, y=return, colour = "Отдача на капитал, % (правая ось)"))+
  geom_line(size = 1)+ #, colour = "#DDCC77"
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_ret$date), to = max(p4_ch2_ret$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(-15,30,5), expand = c(0,0), limits = c(-15,30)) +       
  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "black"),
        #panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .3),
        #panel.grid.minor.y = element_line(colour = "transparent", size = NA),
        #panel.grid.major.x = element_line(colour = "transparent", size = NA),
        #panel.grid.minor = element_line(colour = "transparent", size = NA),
        panel.background = element_rect(fill = NA),
        panel.grid = element_blank(),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        #axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1ret

g1 <- ggplot_gtable(ggplot_build(p4.1prod))
g2 <- ggplot_gtable(ggplot_build(p4.1ret))


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)


leg1 <- g1$grobs[[which(g1$layout$name == "guide-box")]]
leg2 <- g2$grobs[[which(g2$layout$name == "guide-box")]]

g$grobs[[which(g$layout$name == "guide-box")]] <- 
                                  gtable:::cbind_gtable(leg1, leg2, "first")
grid.draw(g)


CairoPDF("plot4.pdf", width=5.23622, height=2.83465)
plot(g)
#plot(double_axis_graph(p4.1prod,p4.1ret))

dev.off()

The data

p4_ch2_prod =
    structure(list(date = structure(c(2010, 2010.25, 2010.5, 2010.75, 
2011, 2011.25, 2011.5, 2011.75, 2012, 2012.25, 2012.5, 2012.75, 
2013, 2013.25, 2013.5, 2013.75, 2014, 2014.25, 2014.5, 2014.75, 
2015, 2015.25, 2015.5, 2015.75, 2016, 2016.25, 2016.5), class = "yearqtr"), 
    productivity = c(86.367867684263, 88.3830463018648, 90.9947166315911, 
    93.0890082484875, 93.8358406567316, 95.415134362968, 95.1392324436027, 
    96.7490649309384, 97.2808331641485, 98.8920648452802, 98.6420849202174, 
    98.9827317138762, 100.118567582808, 99.3807124879942, 100.452579021256, 
    100.048140907942, 101.361645059966, 102.177365696465, 102.220265124015, 
    102.166598060618, 100.880500645703, 99.362767134256, 99.3229078598405, 
    98.7607969743729, 98.8417873432402, 99.153222798328, 98.2951748458741
    )), .Names = c("date", "productivity"), row.names = c(NA, 
27L), class = "data.frame")

p4_ch2_ret =
structure(list(date = structure(c(2010, 2010.25, 2010.5, 2010.75, 
2011, 2011.25, 2011.5, 2011.75, 2012, 2012.25, 2012.5, 2012.75, 
2013, 2013.25, 2013.5, 2013.75, 2014, 2014.25, 2014.5, 2014.75, 
2015, 2015.25, 2015.5, 2015.75, 2016, 2016.25, 2016.5), class = "yearqtr"), 
    return = c(11.7652500842395, 20.1068362958603, 24.4189393391774, 
    27.7603749135956, 22.6909560844267, 19.7512448106456, 9.65853487280893, 
    5.84667147280881, 4.23826276745065, 3.70105654292071, 5.21839712971448, 
    3.46196244414108, 6.08000307844456, -0.0813936964316113, 
    2.57919252646666, 0.206819314044496, 1.70263155186845, 5.21025899295173, 
    3.06177589390397, 4.16006634923697, -4.69833971033449, -10.8930467624443, 
    -11.4996955087892, -14.091528184568, -12.0277510178615, -7.46002412972934, 
    -11.475198069944)), .Names = c("date", "return"), row.names = c(NA, 
27L), class = "data.frame")
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
dkolkin
  • 81
  • 10

2 Answers2

2

I'm not sure what you would like to achieve, but here is a solution with lattice. I also colored the two y-axes differently, although it is not necessary.

library(lattice)
library(latticeExtra)


set.seed(1)
x = rnorm(10)
y1 = rnorm(10)
y2 = rnorm(10)

obj1 = xyplot(y1~x, type = c("p", "a"), ylab.right="")
obj2 = xyplot(y2~x,  type = c("p", "a"))
doubleYScale(obj1, obj2, text = c("y1", "y2"), 
             add.ylab2 = TRUE)

enter image description here

sparrow
  • 1,075
  • 1
  • 10
  • 17
  • 1
    I think you should consider explaining this with `ggplot` since the OP clearly has done a lot of work tweaking the looks of the plot. – Wietze314 Feb 09 '17 at 10:53
  • I agree. I spent almost 3 days learning how to use ggplot2, experimenting and getting a result. So, help in ggplot2 would be much appreciated. – dkolkin Feb 09 '17 at 12:31
1

scale_colour_identity() could be what you are looking for. I have marked changes to your code with # Here comments at the ends of the lines. I've also coloured the y-axis labels. Change back to black if not required.

Also, when you combine the legends, there are 1 null widths in the middle of the combined legend, which results in the legend being too spaced out (in my opinion). Set them to zero for nicer spacing.

library(ggplot2)
library(zoo)
library(gtable)
library(grid)

p4.1prod <- ggplot(data = p4_ch2_prod, aes (x = date, y = productivity, colour = "blue")) +    # Here
  #Производительность труда, 2013=100
  geom_line(size = 1)+
  scale_colour_identity(guide = "legend", label = "Something blue") +   # Here
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_prod$date), to = max(p4_ch2_prod$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(85,105,5), expand = c(0,0), limits = c(85,105)) + #setting the domain of the scale

  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "blue"),   # Here
        panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .2),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "#EDEDED", size = .2),
        panel.grid.minor = element_blank(),
        panel.background = element_rect(fill = "transparent", colour = NA),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1prod 


p4.1ret <- ggplot(data = p4_ch2_ret, aes (x = date, y=return, colour = "red"))+  # Here
  geom_line(size = 1)+ #, colour = "#DDCC77"
  scale_colour_identity(guide = "legend", labels = c("Something red")) +  # Here
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_ret$date), to = max(p4_ch2_ret$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(-15,30,5), expand = c(0,0), limits = c(-15,30)) +       
  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "red"),   # Here
        #panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .3),
        #panel.grid.minor.y = element_line(colour = "transparent", size = NA),
        #panel.grid.major.x = element_line(colour = "transparent", size = NA),
        #panel.grid.minor = element_line(colour = "transparent", size = NA),
        panel.background = element_rect(fill = NA),
        panel.grid = element_blank(),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        #axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1ret

g1 <- ggplotGrob(p4.1prod)
g2 <- ggplotGrob(p4.1ret)


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")   # Here - This line not needed 
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)


leg1 <- g1$grobs[[which(g1$layout$name == "guide-box")]]
leg2 <- g2$grobs[[which(g2$layout$name == "guide-box")]]

leg = gtable:::cbind_gtable(leg1, leg2, "first")              # Here
leg$widths[5:6] = unit(0, "cm")                               # Here

g$grobs[[which(g$layout$name == "guide-box")]] <- leg

grid.draw(g)
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122