When I add a second axis to a ggplotly
object, it does not align to where it should be.
library(ggplot2)
library(plotly)
df <- data.frame(dates = seq.Date(from = as.Date("01/01/1998", "%d/%m/%Y"),
to = as.Date("26/01/1998", "%d/%m/%Y"), by ="day"),
var1 = sample(1:100, 26),
var2 = sample(1:10, 26, replace = TRUE))
p <- ggplot() +
geom_line(data = df, aes(x = dates, y = var1, lty = 'legend')) +
geom_point(data = df, aes(x = dates, y = var2), colour = "red")
ay <- list(
overlaying = "y",
side = "right",
title = "var2",
color = "red"
)
ggplotly(p) %>%
add_lines(x = ~dates, y = ~var1, colors = NULL, yaxis = "y2",
data = df, showlegend = FALSE, inherit = FALSE) %>%
layout(yaxis2 = ay)
The red line at zero (right y axis) is underneath the zero of the left hand axis. Does anyone know whats happening here or how to fix it? I want the second axis to have the same scale as the first axis.
Thanks
Thanks to @Kat, the following works:
library(ggplot2)
library(plotly)
set.seed(23)
df <- data.frame(dates = seq.Date(from = as.Date("01/01/1998", "%d/%m/%Y"),
to = as.Date("26/01/1998", "%d/%m/%Y"), by ="day"),
var1 = sample(1:100, 26),
var2 = sample(1:10, 26, replace = TRUE))
p <- ggplot() +
geom_line(data = df, aes(x = dates, y = var1, lty = 'legend')) +
geom_point(data = df, aes(x = dates, y = var2), colour = "red")
#extract left hand side information
plt <- ggplotly(p)
plt$x$layout$yaxis$range
# [1] -3.6 97.6
plt$x$layout$yaxis$tickvals
# [1] 0 25 50 75
ay <- list(
overlaying = "y",
side = "right",
title = "var2",
color = "red",
#add in values from above
range = c(-3.6, 97.6),
tickvals = c(0, 25, 50, 75)
)
ggplotly(p) %>%
add_lines(x = ~dates, y = ~var1, colors = NULL, yaxis = "y2",
data = df, showlegend = FALSE, inherit = FALSE) %>%
layout(yaxis2 = ay)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.