Here is a start at setting up automatic scaling of the second y axis. I avoided shiny and made the variables V1 and V2 to contain the names of the columns to be plotted. I have not found a way to get a legend to work but I suspect I am not thinking of a well known solution for that.
library(ggplot2)
Date <- c("2021-01-01", "2021-01-05", "2021-01-10", "2021-01-15")
Var1 <- c(0.75, 0.5, 0.63, 0.9)
Var2 <- c(100,200,352, 301)
Var3 <- c(18,22,17,19)
Var4 <- c(1000, 987,905,1002)
DF <- data.frame(Date, Var1, Var2, Var3, Var4)
V1 <- "Var2"
V2 <- "Var4"
LOG <- log2(max(DF[[V1]])/max(DF[[V2]]))
AwayFromZero <- sign(LOG)*ceiling(abs(LOG))
Scaling <- 2^AwayFromZero
ggplot(DF, aes(x=Date)) +
geom_point( aes(y=.data[[V1]], color = V1), size=2, color = "black" ) + #
geom_point( aes(y=.data[[V2]]*Scaling, color = V2), size=2, color = "red") +
scale_y_continuous(
sec.axis = sec_axis(~. / Scaling +0, name = V2)) +
theme_bw()+
theme(axis.line = element_line(colour = "Black"),
axis.title.y = element_text(size=8),
axis.title.y.right = element_text(size=8),
axis.text.y.right = element_text(color = "red"),
axis.title = element_text(face="bold"),
axis.text.x = element_text(angle = 45, hjust=1))
EDIT:
Here is a better version with a legend.
library(ggplot2)
Date <- c("2021-01-01", "2021-01-05", "2021-01-10", "2021-01-15")
Var1 <- c(0.75, 0.5, 0.63, 0.9)
Var2 <- c(100,200,352, 301)
Var3 <- c(18,22,17,19)
Var4 <- c(1000, 987,905,1002)
DF <- data.frame(Date, Var1, Var2, Var3, Var4)
V1 <- "Var2"
V2 <- "Var4"
LOG <- log2(max(DF[[V1]])/max(DF[[V2]]))
AwayFromZero <- sign(LOG)*ceiling(abs(LOG))
Scaling <- 2^AwayFromZero
ggplot(DF, aes(x=Date)) +
geom_point( aes(y=.data[[V1]], color = V1), size=2 ) + #
geom_point( aes(y=.data[[V2]]*Scaling, , color = V2), size=2 ) + #
scale_y_continuous(
sec.axis = sec_axis(~. / Scaling +0, name = V2)) +
scale_color_manual(values = c("black", "red")) +
labs(color = "Variable") +
theme_bw()+
theme(axis.line = element_line(colour = "Black"),
axis.title.y = element_text(size=8),
axis.title.y.right = element_text(size=8),
axis.title = element_text(face="bold"),
axis.text.x = element_text(angle = 45, hjust=1))