r - ggvis - add_legend with multiple data and position legend inside graph -


i'm trying add legends arbitrary text in ggvis plot using data different dataframes. have tried using add_legend() have not idea parameters use. using plot() simple using legend() function has been hard find way using ggvis()

here simple example of have using plot():

df1 = data.frame(x = sample(1:10), y = sample(1:10)) df2 = data.frame(x = 1:10, y = 1:10) df3 = data.frame(x = 1:10, y = sqrt(1:10))  plot(df1) lines(df2$x, df2$y, col = "red") lines(df3$x, df3$y, col = "green") legend("topleft", c("data 2","data 3"), lty = 1, col = c("red","green")) 

now, using ggvis() can plot points , lines different datasets can not find way put legends using add_legend(), here code using ggvis():

df1 %>% ggvis(x=~x,y=~y) %>% layer_points() %>%  layer_paths(x=~x,y=~y,data = df2, stroke := "red") %>%  layer_paths(x=~x,y=~y,data = df3, stroke := "green")  

i appreciate help.

thank you.

edited:

this sample code using 1 data frame , plot()

df = data.frame(x = sample(1:10), y = sample(1:10), x2 = 1:10, y2 = 1:10, y3 = sqrt(1:10) ) plot(df[,c("x","y")]) lines(df$x2, df$y2, col = "red") lines(df$x2, df$y3, col = "green") legend("topleft", c("data 2","data 3"), lty = 1, col = c("red","green")) 

so, came with, following, works:

#add id column df2 , df3 , rbind df2$id <- 1 df3$id <- 2 df4 <- rbind(df2,df3) #turn id factor df4$id <- factor(df4$id)  #then plot df4 using stroke=~id argument #then plot legend #and add df1 separate data df4 %>% ggvis(x=~x,y=~y,stroke=~id) %>% layer_lines() %>%         add_legend('stroke', orient="left") %>%         layer_points(x=~x,y=~y,data = df1,stroke:='black')  

and works:

enter image description here

if move legend position inside plot need try this:

df4 %>% ggvis(x=~x,y=~y,stroke=~id) %>% layer_lines() %>%   #make sure use add relative scales   add_relative_scales() %>%   #values x , y need between 0 , 1   #e.g x-axis 0 @ far-most left point , 1 @ far-right    add_legend("stroke", title = "cylinders",              properties = legend_props(                legend = list(                  x = scaled_value("x_rel", 0.1),                  y = scaled_value("y_rel", 1)                ))) %>%   layer_points(x=~x,y=~y,data = df1,stroke:='black')  

and output:

enter image description here


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -