userJT
userJT

Reputation: 11934

How to put labels over bars in a bar plot in R in ggvis?

Consider a layer_bars() plot in ggvis. How can a user add numbers (labels) above each bar?

Like in graph below: enter image description here

Upvotes: 0

Views: 330

Answers (1)

aosmith
aosmith

Reputation: 36076

You can compute the dataset for the bars and text using compute_count. This is much like the compute_bin example in the ggvis basics docs.

Getting the text aligned takes some work, seethis question/answer based on this open github issue.

mtcars %>% 
    compute_count(~factor(cyl)) %>%
    ggvis(x = ~x_, y = ~count_) %>%
    layer_bars(fill = ~x_) %>%
    layer_text(text := ~x_, prop("x", ~x_, scale = "xcenter"), y = ~count_ + .5, 
             fontSize := 18, align := "center") %>%
    scale_nominal("x", name = "xcenter", padding = .9, points = TRUE)

enter image description here

Upvotes: 1

Related Questions