Search code examples
rsparklines

How to define the color of regular observations in "sparkline" package in R?


I'am using the Sparkline package in a dataset with three observations for years 2000, 2019 and 2020. I have defined colors for max and min values, but I can't find a way to make a dot appear in the remaining observation(s) and give it the color I want.

The following code does not show a dot for 2019:

y <- 1:3
x <- c(2000, 2019, 2020)
sparkline::sparkline(y, xvalues = x, maxSpotColor = "red", minSpotColor = "green")

jQuery documentation says:

valueSpots Specifies which points to draw spots on, and with which colour. Accepts a range. For example, to render green spots on all values less than 50 and red on values higher use {':49': 'green, '50:': 'red'} - New in 2.0

I think I might need to use valueSpots to "draw a black dot on every point but max and min", but I can't find a way to pass such a statement into valueSpots in R. Adding valueSpots = "black" does not work either.


Solution

  • The following works:

    y <- 1:3
    x <- c(2000, 2019, 2020)
    sparkline::sparkline(y, xvalues = x, maxSpotColor = "red", minSpotColor = "green", valueSpots = list("2" = "black"))
    

    enter image description here

    In general, there is the need to specify the mapping for y to the desired colors. To generalize, we can calculate valueSpots as:

    pts_in_between = setdiff(unique(y), c(max(y), min(y)))
    valueSpots = setNames(as.list(rep("black", length(pts_in_between))), pts_in_between)
    

    and then feed into the sparkline, e.g.

    y<-c(100, 300, 400, 300, 200, 500)
    x = c(10, 30, 70, 110, 200, 300)
    pts_in_between = setdiff(unique(y), c(max(y), min(y)))
    valueSpots = setNames(as.list(rep("black", length(pts_in_between))), pts_in_between)
    sparkline::sparkline(values = y, xvalues = x, maxSpotColor = "red", minSpotColor = "green", valueSpots = valueSpots, spotColor = "black")
    

    enter image description here

    Note that I also had to set spotColor = "black" in the function call to ensure that the last point (if not the max or min) is set to "black" instead of "orange".