R:消失的图表

问题描述

我使用的是 R 编程语言。使用以下代码,我制作了这些交互式时间序列图:

library(dplyr)
library(ggplot2)
library(shiny)
library(plotly)
library(htmltools)

library(dplyr)
#generate data
set.seed(123)

######

var = rnorm(731,85,25)
date= seq(as.Date("2014/1/1"),as.Date("2016/1/1"),by="day")
data = data.frame(var,date)

vals <- 90:100
combine <- vector('list',length(vals))
count <- 0
for (i in vals) {
    
    data$var_i = i
    data$new_var_i = ifelse(data$var >i,1,0)
    
    #percent of observations greater than i (each month)
    aggregate_i = data %>%
        mutate(date = as.Date(date)) %>%
        group_by(month = format(date,"%Y-%m")) %>%
        summarise( mean = mean(new_var_i))
    
    #combine files together
    
    aggregate_i$var = i
    aggregate_i$var = as.factor(aggregate_i$var)
    
    count <- count + 1
    combine[[count]] <- aggregate_i
    
}


result_2 <- bind_rows(combine)
result_2$group = "group_b"
result_2$group = as.factor(result_2$group)

a = result_2 %>%
  plot_ly(x=~month,y=~mean,color=~group) %>%
  group_by(group) %>%
  add_lines(frame=~var,hoverinfo = "text",text = ~ paste0("Month: ",month,"<br>","Mean: ",mean,"Total: ",mean(mean))) %>%
  layout(title = list(text = "title"),xaxis = list(tickangle = -90,tickformat = "%m-%Y"))



######


var = rnorm(731,75,2)
date= seq(as.Date("2014/1/1"),date)

vals <- 75:80
combine <- vector('list',"%Y-%m")) %>%
        summarise( mean = mean(new_var_i))
    
    #combine files together
    
    aggregate_i$var = i
    aggregate_i$var = as.factor(aggregate_i$var)
    
    count <- count + 1
    combine[[count]] <- aggregate_i
    
}


result_3 <- bind_rows(combine)
result_3$group = "group_b"
result_3$group = as.factor(result_3$group)

b = result_3 %>%
  plot_ly(x=~month,tickformat = "%m-%Y"))

##### https://stackoverflow.com/questions/66180563/r-updating-hover-text


 a = plot_ly(result_2,x=~month,mean(mean))) %>%
  layout(title = list(text = "title1"),tickformat = "%m-%Y"))


b = plot_ly(result_3,mean(mean))) %>%
  layout(title = list(text = "title2"),tickformat = "%m-%Y"))

#view plots

a

b

当您单独查看这两个图表时,它们可以正常工作:

enter image description here

但是当我尝试使用 plotly::subplot() 命令时,第二个图形消失了:

subplot(a,b,nrows=1)

enter image description here

有谁知道为什么会发生这种情况,有没有办法解决这个问题?在这种情况下,是否还有一种方法可以使用 ggplot2::facet_wrap() 命令将两个图“同步”在一起(例如:R: "tie" two graphs together)?

谢谢

解决方法

您的框架轴不会在任何点相交,因此您不会期望同时看到两个图表 试试这个并按下播放键,您将看到过渡。


subplot(b,a) %>%
  animation_opts(frame = 300,transition = 100,easing="elastic") %>%
  animation_slider(currentvalue = list(prefix=NULL,font=list(color="red",size=40)))

当帧数进入其帧范围时,每个图表都会出现。