0

Change secondary line axis color changes send color for ggplot, but I chose to go with base R, and would like to be able to select the second y axis color.

I have the following data:

df = structure(list(A = c("Q4-17", "Q1-18", "Q2-18", "Q3-18", "Q4-18", 
"Q1-19", "Q2-19", "Q3-19", "Q4-19", "Q1-20", "Q2-20", "Q3-20", 
"Q4-20", "Q1-21", "Q2-21", "Q3-21", "Q4-21", "Q1-22", "Q2-22", 
"Q3-22"), B = c(69.45, 71.1, 74.94, 73.87, 93.61, 91.83, 
95.38, 109.8, 133.75, 125.26, 118.22, 145.65, 144.9757185, 155.3464032, 
184.367033, 179.8121721, 187.235487, 189.1684376, 184.3864519, 
161.5300056), C = c(70.73, 71.73, 74.33, 73.27, 
95.94, 94.38, 95.38, 109.8, 115.32, 116.92, 115.9, 113.87, 106.108147, 
96.84273563, 111.5150869, 110.1228567, 110.7448835, 194.9684376, 
187.7241152, 167.7665553), D = c(260.3, 216.02, 203.72, 
203.52, 300.96, 320.77, 330.5, 413.52, 436.7, 474.96, 463.6, 
501.87, 493.8865461, 497.1760767, 514.9903459, 503.7601267, 510.8362938, 
614.9915546, 603.5761107, 593.660831), E = c(NA, 
NA, NA, NA, NA, NA, NA, NA, 39.237, 35.621, 32.964, NA, 152.137, 
140.743023, 167.809, 170.877, 117.517, 102.691723, 88.8, 76.2445528
)), class = "data.frame", row.names = c(NA, -20L))
df = df %>%
  rowwise() %>%
  mutate(sums = sum(D,E, na.rm = TRUE))
df = df[8:nrow(df),]

and this to generate my plot

x <- seq(1,nrow(df),1)
y1 <- df$B
y2 <- df$D

par(mar = c(5, 4, 4, 4) + 0.3)            
plot(x, y1, col = "#000000",
     type = "l",
     main = "title",
     ylim = c(0, max(df[,2:3])),
     ylab = "Y1",
     xlab = "",
     xaxt = "n")              
axis(1,
     at = seq(from = 13, by = -4, length.out = 4), 
     labels = df$A[seq(from = 13, by = -4, length.out = 4)])
lines(x, df$C, lty = "dashed", col = "#adadad", lwd = 2)
par(new = TRUE)                            
plot(x, df$sums,  col = "#ffa500",             
     axes = FALSE, xlab = "", ylab = "", type = "l")
axis(side = 4, at = pretty(range(y2)), 
     ylim = c(0,max(df[,3:5], na.rm = TRUE)),
     col = "#00aa00")      # Add colour selection of 2nd axis
par(new = TRUE)                            
plot(x, df$D , col = "#0000ff",             
     axes = FALSE, xlab = "", ylab = "", type = "l", lwd = 1)
mtext("y2", side = 4, line = 3)  

but this does not colour my complete second y axis, nor labels, nor title

enter image description here does any one have any suggestions to be able to set entire y2 axis to be #00AA00 - ticks, labels, and title?

frank
  • 3,036
  • 7
  • 33
  • 65

0 Answers0