How to change legend position in ggvis?

2019-08-10 00:48发布

I would like to change the default position of the legend in a ggvis plot.

library(ggvis)
data(mtcars)

mtcars %>% 
    ggvis(x=~wt, y = ~mpg, fill = ~cyl) %>%
    layer_points()

By default, the legend is on the right side. How to put it on the top?

With ggplot you can achieve this simply but I could not find any similar way to do the same with ggvis.

library(ggplot2)
mtcars %>% 
    ggplot(aes(x=wt, y=mpg, fill=cyl)) +
    geom_point() + 
    theme(legend.position = 'top')

This thread suggests that up until now you cannot change the orientation of the legend, but is it true for the position as well?

标签: r ggvis
1条回答
干净又极端
2楼-- · 2019-08-10 01:19

Look at ?add_legend and ?legend_props. I don't think you can do position=top etc, but you could use the x and y ranges of the data to position the legend exactly at the mid-top like with position='top' in ggplot().

mtcars %>% 
    ggvis(x=~wt, y = ~mpg, fill = ~cyl) %>%
    layer_points() %>%
    add_legend("fill", properties=legend_props(
               legend=list(x=scaled_value("x", 3.25), y=scaled_value("y", 40))
    )
)
查看更多
登录 后发表回答