【发布时间】: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