I am trying to plot a graph in ggplot using pivot_longer
but I am struggling to figure out how I can add a second y-axis and plot another series. Some of my data is of different lengths so that is why I am using pivot_longer
but I dont know how to accomodate that with a dual-y axis.
The error I keep getting is the following: "Error: Aesthetics must be either length 1 or the same as the data (48): y
"
Any ideas how I could resolve this? The plot works fine when I comment out geom_line(aes(y=na))+
xstar = 0.85
x1 = c(0.87827, 0.91340, 0.92754, 0.92065, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.85643)
x2 = c(0.68152, 0.78534, 0.82775, 0.82965, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643)
x3 = c(0.67141, 0.77874, 0.82259, 0.82487, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.85643)
a = c(0.30000, 0.67141, 0.77874, 0.77874, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965)
b = c(0.95000, 0.95000, 0.95000, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.85643, 0.85643)
na = c(0, 28, 6, 57, 32, 24, 13, 92, 37, 32, 58, 17, 11, 40, 1)
acc = seq(from = 1, to = (length(a)), by = 1)
na[(length(a))] = NA
x1[(length(a))] = NA
x2[(length(a))] = NA
x3[(length(a))] = NA
totdat = tibble(acc,x1,x2,x3,b,a)
totdat
adjtotdat = pivot_longer(totdat, c(x1,x2,x3))
adjtotdat
pnas = ggplot(adjtotdat, aes(x = acc, y = value, color = name))
pnas + geom_ribbon(aes(ymin=a,ymax=b),fill= "#CCCCCC", color= "#FFFFFF", alpha=0.5)+
geom_line(aes(y=na))+
geom_ribbon(aes(ymin=0,ymax=a),fill= "#333333", color= "#FFFFFF", alpha=0.5)+
geom_ribbon(aes(ymin=b,ymax=1),fill= "#333333", color= "#FFFFFF", alpha=0.5)+ geom_line(size=1) + geom_point(size=2) +
geom_line(aes(y = a), color = "#336600", size = 1) + geom_point(aes(y = a), color = "#336600", size = 2)+
geom_line(aes(y = b), color = "#006633", size= 1) +
geom_point(aes(y = b), color = "#006633", size = 2)+
annotate(geom = "text",x = 1+0.45, y= (min(c(a))-0.02), label = 'bold("Lower Threshold")', size = 3.5, parse = TRUE) +
annotate(geom = "text",x = 1+0.45, y= (max(c(b)-0.02)), label = 'bold("Upper Threshold")', size= 3, parse = TRUE) +
scale_y_continuous(breaks=seq(0,1,0.1),sec.axis = sec_axis(trans=~.*((70)), name="Number of Periods between Accidents")) +
scale_x_continuous(breaks=seq(1,(length(a)),1)) +
geom_hline(aes(yintercept = xstar, linetype ="Ex Ante Court Eff. Effort"), col = "green", size = 1.2)+
scale_linetype_manual(name = "", values = c(2), guide=guide_legend(override.aes = list(color=c("green")))) +
scale_colour_manual(values = c("blue","red","purple","#006633","#336600"),
limits = c("x1","x2","x3","b","a"), name="",
labels = c("Driver 1", "Driver 2", "Driver 3", "Upper Legal Threshold","Lower Legal Threshold"))