Plotting a step function in ggvis

2019-08-16 15:13发布

I would like to plot a step function in ggvis which factors into two colours by a factor variable. In ggplot this can be achieved for this reproducible example by doing:

library(ggplot2)
set.seed(10)
df=data.frame(id=1:100,y=rnorm(100),col=factor(c("MEN","WOMEN")))
ggplot(data=df)+geom_step(aes(id,y,colour=col))

enter image description here

In ggvis I have tried something like this:

library(ggvis)
set.seed(10)
df=data.frame(id=1:100,y=rnorm(100),col=factor(c("MEN","WOMEN")))
df %>% ggvis(x = ~id, y = ~y,stroke := ~col) %>%
layer_paths()

This gives me an empty plot and I'm not sure why. Layer_paths is not quite what I'm looking for, I read here that geom_step from ggplot2 is translated to layer_paths+transform_step in ggvis but I don't understand how that is done. Thank you for your time!

标签: r ggvis
1条回答
别忘想泡老子
2楼-- · 2019-08-16 15:21

I found a soloution for this one using group_by from dplyr and interpolate method from Vega. In addition, I learned that if the goal is to plot each factor in a data.frame, "= ~MyFactorVariable" is used instead of ":= ~ MyFactorVariable". ":=" is used if the value is fixed. e.g. stroke:="red" :

library(dplyr)
library(ggvis)
set.seed(10)
df=data.frame(id=1:100,y=rnorm(100),col=factor(c("MEN","WOMEN")))
df %>% group_by(col)%>%ggvis(x = ~id, y = ~y) %>%
layer_paths(interpolate:="step-after",stroke = ~col)    

enter image description here

查看更多
登录 后发表回答