使用facet_wrap和scale =" free"绘制图表时出错。在情节上

时间:2016-06-09 21:01:16

标签: r ggplot2 plotly

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

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

这是一些示例代码;我为从2000年到2015年的16年期间的12个州创建了一些随机值,我想绘制这些值的时间序列,每个州都有自己的图表和唯一的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)按预期显示:

enter image description here

但是ggplotly(p)被扭曲了:

enter image description here

据我所知,这个主题上有一个先前的主题,但它没有得到解决:

Plotly Facets not translating properly

我将不胜感激。

1 个答案:

答案 0 :(得分:2)

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

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