R语言dygraphs包dyGroup与dySeries函数点形状绘制异常
dygraphs分组绘制时间序列的点形状问题解决
一、dyGroup报错的原因与解决
你遇到的dyGroup报错,是该函数对pointShape参数的单个值处理存在逻辑bug——尽管文档说明参数可传递单个值应用到分组内所有系列,但实际内部会错误解析格式,触发无效值提示。
解决方法:为分组内每个系列重复传递相同的pointShape值,用rep()生成对应长度的向量即可:
dygraphs::dygraph(Example_Data_for_Plotting) %>% dygraphs::dyGroup( colnames(Example_Data_for_Plotting)[grep('Response_A', colnames(Example_Data_for_Plotting))], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = rep('triangle', 3), # 为3个系列重复设置三角形 color = c('blue', 'brown', 'black') ) %>% dygraphs::dyGroup( colnames(Example_Data_for_Plotting)[grep('Response_B', colnames(Example_Data_for_Plotting))], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = rep('square', 3), # 为3个系列重复设置正方形 color = c('blue', 'brown', 'black') )
二、dySeries仅最后一个系列点形状生效的解决
这是dygraphs的渲染优先级问题:连续调用dySeries时,前面的pointShape设置会被后续的全局默认覆盖。解决方式有两种:
方式1:明确指定每个系列的所有参数
dygraphs::dygraph(Example_Data_for_Plotting) %>% # Response_A组:三角形点 dygraphs::dySeries( colnames(Example_Data_for_Plotting)[1], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = 'triangle', color = 'blue' ) %>% dygraphs::dySeries( colnames(Example_Data_for_Plotting)[2], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = 'triangle', color = 'brown' ) %>% dygraphs::dySeries( colnames(Example_Data_for_Plotting)[3], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = 'triangle', color = 'black' ) %>% # Response_B组:正方形点 dygraphs::dySeries( colnames(Example_Data_for_Plotting)[4], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = 'square', color = 'blue' ) %>% dygraphs::dySeries( colnames(Example_Data_for_Plotting)[5], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = 'square', color = 'brown' ) %>% dygraphs::dySeries( colnames(Example_Data_for_Plotting)[6], drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5, pointShape = 'square', color = 'black' )
方式2:先设置全局默认,再分组覆盖
简化重复参数,先通过dyOptions设置全局绘图规则,再为不同分组覆盖点形状:
dygraphs::dygraph(Example_Data_for_Plotting) %>% dygraphs::dyOptions(drawPoints = TRUE, strokeWidth = 0, pointSize = 2.5) %>% # Response_A组:覆盖为三角形 dygraphs::dySeries(colnames(Example_Data_for_Plotting)[1:3], pointShape = 'triangle', color = c('blue', 'brown', 'black')) %>% # Response_B组:覆盖为正方形 dygraphs::dySeries(colnames(Example_Data_for_Plotting)[4:6], pointShape = 'square', color = c('blue', 'brown', 'black'))
总结
dyGroup的报错属于函数参数处理bug,传递对应长度的重复向量即可规避。dySeries的点形状覆盖问题是渲染优先级导致的,明确指定参数或全局默认+分组覆盖均可解决。
内容的提问来源于stack exchange,提问作者David Moore
相关产品推荐
相关产品推荐

