R语言 ggplotly的第二个轴未与第一个轴对齐

e4eetjau  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(125)

当我向ggplotly对象添加第二个轴时,它没有与它应该在的位置对齐。

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)

在零点的红线(右边的y轴)在左手的零点的下面。有人知道这里发生了什么或者如何修复它吗?我希望第二个轴和第一个轴有相同的比例。
谢谢

ws51t4hk

ws51t4hk1#

感谢@Kat,以下作品:

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)

相关问题