Search code examples
rggplot2plotlyboxplot

A 1-D number line/boxplot style chart in R


I am trying to generate a SIMPLE rendering to show the x-range of values as compared to thresholds (red, yellow, green). As inputs, I have lists of numbers representing the number that should be at the leftmost point on the bar, and the number that should be on the rightmost point of the bar:

x1 <- c(44, 73)
boxplot(x1, ylim=c(0,100), horizontal=TRUE, boxwex=0.2)

enter image description here

Ideally, I would be able to produce something that looks like this, with a threshold of red in the background for numbers from [0 to 48), yellow for [48 to 69], and red for (69 to 100]. Ideally there would also be a ggtitle style title.

enter image description here

I have already tried several options with plotly, ggplot2, and stripchart but all fail to generate anything close to my target. Does anyone have any ideas?


Solution

  • You could use the shapes argument in layout for a plotly graph like this:

    library(plotly)
    library(tibble)
    library(purrr)
    
    lims <- local({
      lims <- c(0L, 48L, 69L, 100L)
      tibble(left = head(lims, -1L),
             right = tail(lims, -1L),
             color = c("firebrick", "darkorange", "forestgreen"))
    })
    
    shps <- pmap(lims, function(left, right, color) {
      list(
        type = "rect",
        fillcolor = color,
        line = list(width = 0),
        x0 = left,
        x1 = right,
        y0 = 0,
        y1 = 1,
        layer = "below"
      )
    })
    
    shps <- c(shps,
              list(
                list(
                  type = "rect",
                  fillcolor = "#000",
                  line = list(color = "#fff", width = 2),
                  x0 = 44,
                  x1  = 73,
                  y0 = .35,
                  y1 = .65,
                  layer = "below"
                )
              )
    )
    
    plot_ly(width = 1000, height = 200) %>% 
      add_text(x = 60, y = .5, text = "Add a Label", textfont = list(color = "#fff")) %>% 
      layout(shapes = shps,
             xaxis = list(ticks = "outside", zeroline = FALSE, showgrid = FALSE),
             yaxis = list(showticklabels = FALSE, zeroline = TRUE, showgrid = FALSE,
                          zerolinecolor = "#000")) 
    

    Plotly Graph with 3 colored rectangles and a label