I have two ggplot2 that I want to transform to ggplotly with the idea of interaction between both figures. The problem is that the DF for the second needs a transformation. I know how to do it with plotly from scratch but I need do it from ggplot2.
Here is my code:
require(dplyr)
require(lubridate)
require(ggplot2)
require(gridExtra)
require(plotly)
My data:
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))
This is the final output with ggplot2
without interaction
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)
This is the my proposal to do it from ggplot2 to ggplotly (and doesn't work)
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)
How has to be done it? thanks
My suggestion is to use
ggplotly()
in each plot and than usesubplot()
fromplotly
This isn't the pretty plot ever, but I think that it will help you:
The output: