I am working on a use-case to achieve the attached expected output (ignore the alignment of legend names) using R.
library(ggplot2)
library(tidyverse)
library(reshape2)
#Creating a dataframe with use-case specific variables. (Missing values are intentional to replicate real-time data)
df = data.frame(
Year = 2006:2025,
Survey = c(40.5, 39.0, NA, NA, NA, NA, 29.9, NA, NA, NA, 21.6,
NA, NA, NA, NA, NA, NA, NA, NA, NA),
WhatIf = c(NA, NA, NA, NA, NA, NA, 29.9, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, 14.9),
AARR = c(NA, NA, NA, NA, NA, NA, 29.9, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, 13.0),
Current = c(NA, NA, NA, NA, NA, NA, 29.9, 27.6, 25.4, 23.4, 21.6,
19.9, 18.4, 16.9, 15.6, 14.4, 13.3, NA, 12.2, 11.3)
)
# Method 1
#Data transformation using melt package
# df_long <- melt(df,id.vars = "Year")
#
# ggplot(data=df_long,aes(x=Year,y=value, colour=variable)) +geom_line() +
# theme(legend.position="bottom")
#Method 2
#Plot and adding lines - Year vs. rest of the columns
plot(df$Year, df$Survey, type = "o", col = "dark grey", pch = "o", lty = 1, ylim = c(0,max(df$Survey, na.rm = T)), ylab = "Survey")
points(df$Year, df$WhatIf, col="orange" )
lines(df$Year, df$WhatIf, col="orange",lty=2)
points(df$Year, df$AARR, col="black")
lines(df$Year, df$AARR, col="black", lty=2)
points(df$Year, df$Current, col="dark blue")
lines(df$Year, df$Current, col="dark blue", lty=2)
legend(1, 100, legend=c("Survey","WhatIf", "AARR","Current"),
col=c("dark grey","orange","black", "dark blue"),
lty=c(1,2,2,2), ncol=1)
Created on 2020-06-30 by the reprex package (v0.3.0)
I have tried two methods in R to simulate a basic plot with legends and two y-axes, but unfortunately, I am unable to produce the expected output. So the columns Current, WhatIf, AARR would be dashed lines with different colours and Survey column is represented by a symbol "o"
.
Any recommendations on the approach are greatly appreciated.