Search code examples
rlattice

Change axis label colors and legend line colors using xyplot and doubleYscale


I am trying to create a plot with dual y-axes using the xyplot and doubleYscale functions of latticeExtra. How do I change the axis label colors of the left and right y-axis as well as legend line colors to the same as the line colors in the plot? These now plot in blue and pink, but should be same as the lines in the plot below. Please see reproducible code example and plot below:

library(lattice)
library(latticeExtra)

# Create the data frame.
My_DataFrame <- data.frame(
  emp_id = c (1:5), 
  salary = c(623.3,515.2,611.0,729.0,843.25), 
  weight = c(80,90,92,93,91),
  start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-05-11", "2014-11-15","2015-03-27")),
  stringsAsFactors = FALSE
)
# Print the data frame.         
print(My_DataFrame) 

obj1 <- xyplot(salary ~ start_date, My_DataFrame, type = "l", lwd = 2, col = "#6F99ADFF", col.lab = "black", ylim = seq(0,1000,100), scales = list(x=list(cex=1.2), y=list(cex=1.2)), xlab = list("", fontsize = 22), ylab = list("Hello", fontsize = 18), ylab.right = list("There", fontsize = 18))

obj2 <- xyplot(weight ~ start_date, My_DataFrame, type = "l", lwd = 2, col = "#E18727FF")

doubleYScale(obj1, obj2, col = c("#6F99ADFF","#E18727FF"), text = c("salary", "weight"), add.ylab2 = FALSE)

enter image description here


Solution

  • Add par.settings = list(superpose.line = list(col=c("#6F99ADFF", "#E18727FF"))), in your code:

    obj1 <- xyplot(salary ~ start_date, My_DataFrame, type = "l", lwd = 2, 
                   col = "#6F99ADFF", col.lab = "black", 
                   par.settings = list(superpose.line = list(col=c("#6F99ADFF", "#E18727FF"))),
                   ylim = seq(0,1000,100), 
                   scales = list(x=list(cex=1.2), 
                                 y=list(cex=1.2)), 
                   xlab = list("", fontsize = 22), 
                   ylab = list("Hello", fontsize = 18, col="#6F99ADFF"), ylab.right = list("There", fontsize = 18, col="#E18727FF"))
    
    obj2 <- xyplot(weight ~ start_date, My_DataFrame, type = "l", lwd = 2, col = "#E18727FF")
    
    doubleYScale(obj1, obj2, col = c("#6F99ADFF","#E18727FF"), text = c("salary", "weight"), add.ylab2 = F)
    

    enter image description here