Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a plot title to ggvis

Tags:

I want to add a title to a ggvis plot. I can't find an example anywhere. It's simple to do with other R plots, e.g.

library(ggplot2) library(ggvis) x <- 1:10 y <- x^2 df <- data.frame(x, y)  plot(x, y, main = "Plot Title")  # Base R with title ggplot(df, aes(x, y)) + geom_point() + ggtitle("Plot Title")  # ggplot2 with title df %>% ggvis(~x, ~y) %>% layer_points()  # ggvis but no title?? 

Feel like I'm missing something obvious. Any help appreciated.

like image 853
Anto Avatar asked Jul 29 '14 15:07

Anto


Video Answer


2 Answers

Well, seems like it has not been implemented (or documented?) yet. I'm pretty sure this will be added soon. For now, you can use a dirty hack like so:

df %>% ggvis(~x, ~y) %>% layer_points() %>%    add_axis("x", title = "X units") %>%   add_axis("x", orient = "top", ticks = 0, title = "Plot Title",            properties = axis_props(              axis = list(stroke = "white"),              labels = list(fontSize = 0))) 

Furthermore, if you would like to use this hack multiple times, you can create a shorthand for it.

add_title <- function(vis, ..., x_lab = "X units", title = "Plot Title")  {   add_axis(vis, "x", title = x_lab) %>%      add_axis("x", orient = "top", ticks = 0, title = title,              properties = axis_props(                axis = list(stroke = "white"),                labels = list(fontSize = 0)              ), ...) } df %>% ggvis(~x, ~y) %>% layer_points() %>% add_title() #same as before df %>% ggvis(~x, ~y) %>% layer_points() %>% add_title(title = "Hello", x_lab = "ton") 

Edit:

Now you can set both the main title and the x axis label simultaneously, fixing the overlap mentioned below.

like image 105
tonytonov Avatar answered Dec 31 '22 17:12

tonytonov


Also, to change the font size of the title use this code (adapted from @tonytonov's answer):

add_title <- function(vis, ..., x_lab = "X units", title = "Plot Title")  {   add_axis(vis, "x", title = x_lab) %>%      add_axis("x", orient = "top", ticks = 0, title = title,              properties = axis_props(                axis = list(stroke = "white"),                title = list(fontSize = 32),                labels = list(fontSize = 0)              ), ...) } 
like image 35
resamsel Avatar answered Dec 31 '22 18:12

resamsel