如何在ggvis中同时缩放点大小和颜色?

时间:2017-12-09 05:14:47

标签: r plot scale ggvis

考虑像这样的data.frame:

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

使用ggvis,我想生成一个点线图,其中该行按group分组。 type==3点的大小应为100,而type==1type==2的点大小均为50.点的颜色应为green,{{1与blueredtype1对应的{}}和type2。这是我的type3代码:

ggvis

我收到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") 的错误。 为什么会这样,我该如何解决?

2 个答案:

答案 0 :(得分:1)

事实证明,scale_nominal("size",domain = c(1,2,3), range = c(50,50,100))应替换为scale_nominal("size",domain = c(1,2,3), range = c('50','50','100'))

答案 1 :(得分:0)

错误的罪魁祸首是为range定义的超过2个值。 range的定义建议:For numeric values, the range can take the form of a two-element array with minimum and maximum values.

For ordinal data, the range may by an array of desired output values, which are mapped to elements in the specified domain。在这种情况下,应该在字符中定义值。

这应该可以解决您的错误。