Sarobinson Sarobinson - 3 months ago 57
R Question

Display and fill multiple layer_text layers in ggvis

I am having trouble using the "fill" property for more than one text layer:

Month = seq(1,12)
Median_Peak_Duration = c(6,5,4,3,1,2,2,3,4,4,5,5.5)
PeakyMonth = ifelse(Median_Peak_Duration > 3, 'Non-Peaky', 'Peaky')
testDat = data.frame(Month, Median_Peak_Duration,PeakyMonth)

testDat %>%
ggvis(x = ~Month, y = ~Median_Peak_Duration, fill = ~PeakyMonth) %>%
layer_bars(width = .8) %>%
# Annotation
layer_lines(x = ~Month, y = 3, strokeDash := 6, strokeWidth := 3) %>%
layer_text(x = 6, y = 4.5, text:= "Some more Text",
fontSize := 12, align := "center", baseline := "top", fill := "black") %>%
layer_text(x = 6, y = 3, text:= "Some Text",
fontSize := 12, align := "center", baseline := "top", fill := "black")


This causes no text to display while this works:

testDat %>%
ggvis(x = ~Month, y = ~Median_Peak_Duration, fill = ~PeakyMonth) %>%
layer_bars(width = .8) %>%
# Annotation
layer_lines(x = ~Month, y = 3, strokeDash := 6, strokeWidth := 3) %>%
layer_text(x = 6, y = 4.5, text:= "Some more Text",
fontSize := 12, align := "center", baseline := "top", fill := "black")

Answer

To avoid needing fill in layer_text to control the color of the text you could move it to be inside layer_bars.

I think you are also going to want to put the text you are plotting into a data.frame, otherwise it looks like the text gets plotted many times and looks funny (this would be like what happens withggplot2:geom_text`).

One option:

testDat %>%
    ggvis(x = ~Month, y = ~Median_Peak_Duration) %>%
    layer_bars(width = .8, fill = ~PeakyMonth) %>%
    # Annotation
    layer_lines(x = ~Month, y = 3, strokeDash := 6, strokeWidth := 3) %>%
    layer_text(data = data.frame(x = 6, y = 4.5, text = "Some more text"), 
             x = ~x, y = ~y, text := ~text,
             fontSize := 12, align := "center", baseline := "top") %>%
    layer_text(data = data.frame(x = 6, y = 3, text = "Some Text"),
             x = ~x, y = ~y, text := ~text,
             fontSize := 12, align := "center", baseline := "top")

If leaving fill in overall ggvis:

testDat %>%
    ggvis(x = ~Month, y = ~Median_Peak_Duration, fill = ~PeakyMonth) %>%
    layer_bars(width = .8) %>%
    # Annotation
    layer_lines(x = ~Month, y = 3, strokeDash := 6, strokeWidth := 3) %>%
    layer_text(data = data.frame(x = 6, y = 4.5, text = "Some more text"), 
             x = ~x, y = ~y, text := ~text,
             fontSize := 12, align := "center", baseline := "top", fill := "black") %>%
    layer_text(data = data.frame(x = 6, y = 3, text = "Some Text"),
             x = ~x, y = ~y, text := ~text,
             fontSize := 12, align := "center", baseline := "top", fill := "black")

enter image description here