1

I am trying to color a set of geographical points by a time variable using the tmap function tm_dots, but it keeps treating the time variable as a categorical variable. Is there a way to use a POSIXct column as a continuous variable? Some example code demonstrating the problem is:

library(sf)
library(tmap)
df = data.frame(lon=1:20,lat=1:20,ts=as.POSIXct(paste0('2020-01-',1:20)))
df = st_as_sf(df,coords=c("lon","lat"),crs=4326)

tm_shape(df) + tm_dots(col="ts")

Code output

One "solution" would be to convert the dates into a number (e.g., number of days since the earliest date), and then use this numeric variable to color the points, perhaps using different labels in the legend to replace the numbers with the original dates, but this seems like a lot of work and is unlikely to produce satisfactory results without a lot of fiddling.

user3004015
  • 617
  • 1
  • 7
  • 14

1 Answers1

0

You will need to declare a palette; for a possible approach consider this piece of code. What it does is it uses a generic sequential palette. Also note the silent default of stretch.palette = TRUE in a generic tmap::tm_symbols() call - this leads to interpolating colors, i.e. you can have more values than your palette has defined colors.

library(sf)
library(tmap)
df = data.frame(lon=1:20,lat=1:20,ts=as.POSIXct(paste0('2020-01-',1:20)))
df = st_as_sf(df,coords=c("lon","lat"),crs=4326)

tm_shape(df) + tm_dots(col="ts",
                       palette = "seq") # also consider "Blues"

a plot with dots in sequiential palette

Jindra Lacko
  • 7,814
  • 3
  • 22
  • 44
  • I don't think this really answers the question as defining a palette will change the colors used to show the data, but looking at the legend it appears that the data is still being treated as a categorical variable. This will work OK if the dates are strictly linear without gaps as they are in the simple example I gave, but if you have dates with gaps and that are not simply dates, but also times, then this will not work as expected. – user3004015 Feb 02 '23 at 15:06
  • I am afraid this is as far as tmap will let us go; if you require the intensity of a color to map to a numeric variable you will be better off using `ggplot::geom_sf()` and map color to an aesthetic using ggplot techniques. – Jindra Lacko Feb 02 '23 at 15:14
  • tmap will handle coloring by a numerical variable just fine. It is date variables that are problematic. Is this what you meant? – user3004015 Feb 03 '23 at 16:04