如何在Plotly R的scattermapbox类型地图中创建虚线
解决Plotly scattermapbox虚线绘制问题
问题原因
Plotly的scattermapbox类型的line参数目前不支持dash或linetype属性,直接设置这两个参数不会生效。
有效解决方案:使用Mapbox图层绘制虚线
通过layout中的mapbox$layers添加自定义线图层,Mapbox线图层支持dasharray参数定义虚线样式,适配所有缩放级别,不会出现标记随缩放变形的问题。
修改后的代码
plot_ly() %>% layout( mapbox = list( style = "carto-positron", zoom = 6, center = list(lon=21, lat=43), # 添加自定义虚线图层 layers = list( list( type = "line", source = list( type = "FeatureCollection", features = list( list( type = "Feature", geometry = list( type = "LineString", coordinates = list( # 坐标顺序为[经度, 纬度],注意与scattermapbox的顺序相反 c(21.5869,42.2628), c(21.5625,42.343), c(21.7783,42.6513), c(21.7534,42.7009), c(21.66,42.6828), c(21.5717,42.7294), c(21.5717,42.7294), c(21.4095,42.7487), c(21.4351,42.8723), c(21.2683,42.9085), c(21.228,43.0056), c(21.1695,43.0165), c(21.1177,43.1198), c(20.9236,43.1461), c(20.8197,43.2725), c(20.6184,43.1926), c(20.6824,43.1165), c(20.6589,43.0287), c(20.506,42.9562), c(20.5121,42.8871), c(20.3529,42.8334), c(20.3529,42.8334) ) ) ) ) ), paint = list( "line-color" = "red", "line-width" = 1, # 定义虚线样式:[实线段长度, 空白段长度],可调整数值改变虚实比例 "line-dasharray" = c(2, 2) ) ) ) ) )
关键说明
- Mapbox图层坐标顺序为**[经度, 纬度]**,与
scattermapbox的[纬度, 经度]顺序相反,需注意转换 line-dasharray参数控制虚线样式,比如c(2,2)代表2个单位实线、2个单位空白,可根据需求调整数值- 该方式绘制的虚线不会随地图缩放变形,完全符合要求的展示效果
内容的提问来源于stack exchange,提问作者stallingOne
相关产品推荐
相关产品推荐

