ggvis - add_legend with multiple data and position legend inside graph

社会主义新天地 提交于 2019-12-05 21:04:47

So, what I came up with, is the following, which works:

#add an id column for df2 and df3 and then rbind
df2$id <- 1
df3$id <- 2
df4 <- rbind(df2,df3)
#turn id into a factor
df4$id <- factor(df4$id)

#then plot df4 using the stroke=~id argument
#then plot the legend
#and finally add df1 with a 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 it works:

If you would like to move the legend to a position inside the plot then you need to try this:

df4 %>% ggvis(x=~x,y=~y,stroke=~id) %>% layer_lines() %>%
  #make sure you use add relative scales
  add_relative_scales() %>%
  #values for x and y need to be between 0 and 1
  #e.g for the x-axis 0 is the at far-most left point and 1 at the 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 the output:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!