Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

r - Leaflet colours for polylines

I would like to use a basic data.frame to get three polylines each of different colours

I am currently using the below code as an example.

require(leaflet)
df <- data.frame(lat=c(rnorm(20,50),rnorm(40,0),rnorm(40,-30)),
                 lon=rnorm(100),
                 group=rep(c("a","b","c"),times=c(20,40,40)),
                 col=rep(rainbow(3,alpha=NULL),times=c(20,40,40)))
leaflet(df) %>% addTiles() %>% addPolylines(lng=~lon,lat=~lat,color=~col)

But I get one continous line and and not the three separate lines for each group.

I can separate the lines but doing an very inelegant trick of:

df_a <- rbind(df[df$group=="a",],data.frame(lat=NA,lon=NA,group="a",col=NA))
df_b <- rbind(df[df$group=="b",],data.frame(lat=NA,lon=NA,group="b",col=NA))
df_c <- rbind(df[df$group=="c",],data.frame(lat=NA,lon=NA,group="c",col=NA))
df <- rbind(df_a,df_b)
df <- rbind(df,df_c) 

before the leaflet function, but it still does not solve the colour problem.

Any help to get the three polylines different colours would be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a way to automate for each group in your dataset:

map <-  leaflet(df)
map <- addTiles(map)
for( group in levels(df$group)){
        map <- addPolylines(map, lng=~lon,lat=~lat,data=df[df$group==group,], color=~col)
        }
map

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...