Considering a data.frame like this:
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)))
Using ggvis
, I want to generate a point-line plot in which the line is grouped by group
. The size of points with type==3
should be 100 while the size of points withtype==1
and type==2
are all 50. The colour of the points should be green
, blue
and red
corresponding to type1
,type2
and type3
. Here is my ggvis
code:
df <- data.frame(df,id=1:nrow(df))
all_values <- function(x) {
if(is.null(x)) return(NULL)
row <- df[df$id == x$id, ]
paste0(names(row), ": ", format(row), collapse = "<br />")
}
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",domain = c(1,2,3), range = c(50,50,100)) %>%
scale_nominal("fill",domain = c(1,2,3), range = c('green','blue','red')) %>%
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")
I get the error of Error: length(x) not less than or equal to 2
.
Why this happened and how can I fix it?
It turns out that scale_nominal("size",domain = c(1,2,3), range = c(50,50,100))
should be replaced by scale_nominal("size",domain = c(1,2,3), range = c('50','50','100'))
.