在 plotly 中使用 facet_wrap 和 scales = "free" 绘制图表时出错

Error plotting chart with facet_wrap and scales = "free" in plotly

我有一个包含各种类别(方面)的时间序列,我正在尝试使用 ggplot2facet_wrap 功能创建图表并将其上传到 plotly

如果我设置 scales = "fixed",我没有问题:图表在我的计算机和 plotly 上看起来都很好。但是如果我设置 scales = "free",如下面的代码,那么我电脑上的 ggplot2 看起来不错,但是 plotly 版本没有正确显示(无论是在我的电脑上还是在网络上).

这是一些示例代码;我为 12 个州创建了一些随机值,涵盖从 2000 年到 2015 年的 16 年期间,我想绘制这些值的时间序列,每个州都有自己的图表和唯一的 y 轴。

library(ggplot2)
library(plotly)

set.seed(1) 
states = sample(state.name, 12) ## create random list of 12 states 

## create random data with values for state and by year 
dat <- data.frame(Year = rep(2000:2015, times = 12),
              State = rep(states, each = 16),
              Value = rnorm((12*16), mean = 5, sd = 2))

## plot data with facet_wrap for each state
p <- ggplot(dat, aes(Year, Value)) + geom_line() + 
    facet_wrap(~ State, ncol = 4, scales = "free")
p
ggplotly(p)

ggplot2 命令 (p) 按预期显示:

但是ggplotly(p)被扭曲了:

据我所知,之前有一个帖子讨论过这个话题,但没有解决:

Plotly Facets not translating properly

如有任何帮助,我将不胜感激。

如果您对替代方案持开放态度,可以尝试使用原生 plotlysubplot。尝试:

dat$id <- as.integer(dat$State)
p <- plot_ly(dat, x = Year, y = Value, group = State,
             xaxis = paste0("x", id), marker=list(color="black"))
p <- layout(
    subplot(p, nrows=3, margin = 0.05),
    xaxis = list(title = "Arizona"),
    xaxis2 = list(title = "Connecticut"),
    xaxis3 = list(title = "Florida"),
    xaxis4 = list(title = "Georgia"),
    xaxis5 = list(title = "Indiana"),
    xaxis6 = list(title = "Maine"),
    xaxis7 = list(title = "Nebraska"),
    xaxis8 = list(title = "Nevada"),
    xaxis9 = list(title = "New Hampshire"),
    xaxis10 = list(title = "South Dakota"),
    xaxis11 = list(title = "Tennessee"),
    xaxis12 = list(title = "Texas"), 

    yaxis = list(title = "Value"),
    yaxis2 = list(title = ""),
    yaxis3 = list(title = ""),
    yaxis4 = list(title = ""),
    yaxis5 = list(title = "Value"),
    yaxis6 = list(title = ""),
    yaxis7 = list(title = ""),
    yaxis8 = list(title = ""),
    yaxis9 = list(title = "Value"),
    yaxis10 = list(title = ""),
    yaxis11 = list(title = ""),
    yaxis12 = list(title = ""), showlegend = FALSE)
p