简体   繁体   中英

How to produce a ggvis plot similar to this ggplot2 one

I'm familiar with ggplot2, here is the ggplot2 code for producing what I want:

   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'))

在此处输入图片说明

This plot takes line group, line type, point color, point size and x-axis time format into consideration. I want to produce a similar plot just like this with ggvis and use add_tooltip to display the point's information (all variables) when hovering. But I found it hard to specify the blue, red and green colour. The ggvis code that I tried is like this:

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")

Could someone offer me some help?

This is my replication of your ggplot2 graph:

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

Note that to perfectly replicate your original plot, I add a auxiliary mapping to opacity to set the lines apart while keeping stroke mapping to type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM