Plotting a step function in ggvis

我的梦境 提交于 2020-01-17 04:16:27

问题


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

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!


回答1:


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)    



来源:https://stackoverflow.com/questions/31395410/plotting-a-step-function-in-ggvis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!