【问题标题】:two ggplot2 previous to transform to plotly to obtain interactive之前的两个ggplot2转换为plotly获得交互
【发布时间】:2020-07-23 05:50:57
【问题描述】:

我有两个 ggplot2,我想通过两个图形之间的交互来转换为 ggplotly。 问题是第二个的 DF 需要转换。我知道如何从头开始使用 plotly,但我需要从 ggplot2 开始。

这是我的代码:

require(dplyr)
require(lubridate)
require(ggplot2)
require(gridExtra)
require(plotly)

我的数据:

df1<-tibble(date=seq.Date(as.Date("2000-01-01"),as.Date("2003-12-31"),by="1 month"),
           value=sample(10:20,48,replace = TRUE))

df2<-df1 %>% mutate(year=year(date))

df3<-df2 %>% 
  group_by(year) %>% 
    summarise(max=max(value),mean=mean(value),min=min(value))

这是与ggplot2 没有交互的最终输出

graf1<-ggplot(df2)+geom_line(aes(date,value,color=factor(year),group=year),size=4)

graf2<-ggplot(df3)+
          geom_segment(aes(x=year,xend=year,y=min,yend=max,color=factor(year),group=year),size=10)+
          geom_point(aes(year,mean),size=2)

grid.arrange(graf1,graf2,nrow=2)

这是我从 ggplot2 到 ggplotly 的建议(但不起作用)

df2Linked<-highlight_key(df2,~year)

graf1<-ggplot(df2Linked)+geom_line(aes(date,value,color=factor(year),group=year),size=4)
graf1Ly<-ggplotly(graf1)%>% highlight(on = "plotly_hover", off = "plotly_deselect")
#it works!!

#**that NOT WORK in this way**, as its an object of class "c('SharedData', 'R6')"
df3<-df2Linked %>% group_by(year) %>% summarise(max=max(value),mean=mean(value),min=min(value))

graf2<-ggplot(df3)+geom_segment(aes(x=year,xend=year,y=min,yend=max,color=factor(year),group=year),size=10)+geom_point(aes(year,mean),size=2)
graf2Ly<-ggplotly(graf2)%>% highlight(on = "plotly_hover", off = "plotly_deselect")

subplot(graf1Ly,graf2Ly,nrows=2)

该怎么做呢? 谢谢

【问题讨论】:

    标签: r ggplot2 r-plotly ggplotly


    【解决方案1】:

    我的建议是在每个情节中使用ggplotly(),而不是使用plotly中的subplot()

    这不是一个漂亮的情节,但我认为它会帮助你:

    graf1<-ggplot(df2)+
            geom_line(aes(date,value,color=factor(year),group=year),size=4) + 
            labs(color='Year') 
    
    graf2<-ggplot(df3)+
              geom_segment(aes(x=year,xend=year,y=min,yend=max,color=factor(year),group=year),size=10)+
              geom_point(aes(year,mean),size=2) + 
              labs(color='Year')
    
    
    
    subplot(ggplotly(graf1),ggplotly(graf2), nrows = 2)
    

    输出:

    【讨论】:

    • 谢谢,但这样只能通过传说进行交互。我想使用“highlight_key”或类似我在图表中单击的东西在其他图表中做出反应
    • 嗯,也许你可以尝试在每个情节中指定legend_group你想要放入highlight_key的东西。但我不确定。
    猜你喜欢
    • 2016-04-02
    • 2017-08-06
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多