如何生成类似于这个ggplot2的ggvis图

时间:2017-12-08 16:09:42

标签: r ggplot2 ggvis

我熟悉ggplot2,这里是生成我想要的ggplot2代码:

   library(ggplot2)
   library(scales)
   set.seed(100)
   df <- data.frame(t = rep(seq(from=as.POSIXct('00:15:00',format='%H:%M:%S'),
                             to=as.POSIXct('24:00:00',format='%H:%M:%S'),by='15 min'),times=2),
                     y = c(rnorm(96,10,10),rnorm(96,40,5)),
                     group = factor(rep(1:2,each=96)),
                     type = factor(rep(1:3,each=64)))

  ggplot(data=df,aes(x=t,y=y,col=type))+geom_point(aes(size=type))+
  geom_line(aes(group=group))+
  scale_x_datetime(labels = date_format('%H:%M', tz = "Asia/Taipei"),
                   breaks = date_breaks('2 hours'))+
  scale_colour_manual(values = c('red','blue','green'))

enter image description here

该图考虑了线组,线型,点颜色,点大小和x轴时间格式。我希望使用ggvis生成类似的情节,并使用add_tooltip在悬停时显示该点的信息(所有变量)。但我发现很难指定蓝色,红色和绿色。 ggvis 我试过的代码是这样的:

df <- data.frame(df,id=1:nrow(df))
    ggvis(data=df,x=~t,y=~y,stroke=~group) %>% 
      layer_points(fill=~type,size=~type, key:=~id, fillOpacity := 0.5,
                   fillOpacity.hover := 0.8,size.hover := 500) %>% 
      scale_nominal("size", range = c(50,200)) %>%
      layer_lines() %>% 
      add_tooltip(all_values,'click') %>%
      add_legend(scales=c("fill","size"), properties = legend_props(legend = list(y = 150))) %>%
      set_options(duration = 0) %>% 
      add_axis(type="x",format="%H:%M")

有人可以给我一些帮助吗?

1 个答案:

答案 0 :(得分:0)

这是我对ggplot2图的复制:

ggvis(data=df,x=~t,y=~y,opacity=~group,stroke=~type) %>% 
  layer_points(fill=~type,size=~type, key:=~id, fillOpacity := 0.5,fillOpacity.hover := 0.8,size.hover := 500) %>% 
  layer_lines() %>%
  scale_nominal("size", range = c(50,200)) %>%
  add_tooltip(all_values,'click') %>%
  add_legend(scales=c("fill","size"), properties = legend_props(legend = list(y = 150))) %>%
  set_options(duration = 0) %>% 
  add_axis(type="x",format="%H:%M") %>%
  scale_ordinal("fill", range = c("red", "blue", "green")) %>%
  scale_ordinal("stroke", range = c("red", "blue", "green")) %>%
  scale_ordinal("opacity", range = c(1, 1))

click to see my plot

请注意,为完美地复制原始图,我向不透明度添加了辅助映射,以将线条分开,同时保持笔触映射为类型