4

I have a SpatialPolygonsDataFrame with columns containing hex-color values. I want to draw the map like this with the package tmap:

tm_shape(full.shp) + tm_fill(col="konf1900")

But then it is treated as categorial variable, resulting in this: screenshot 2016-11-01 10 15 53

I am not sure how to tell tmap that it should plot the color values directly on the map...

Can anyone help on this?

edit: see the answers below - the problem was that the dataframe column was no encoded as.character. I think this might help someone sometime...

Mario
  • 2,393
  • 2
  • 17
  • 37
  • Apperently, the `konf1900` variable contains color values. In such a case `tm_fill` uses these values to fill the polygons. As far as I can see, this is the case in your plot. It isn't therefore clear to me what your problem is .... – Jaap Nov 01 '16 at 10:45
  • no, unfortunately, it doesn't use the color values for the filling - for example, compare the first legend entry: #08306B this should be dark blue, not green. Also, I can change the color using palette-command, which should not be the case if it was taking the color values. It treats the variable as a categorial variable. – Mario Nov 01 '16 at 10:49

2 Answers2

4

Apparently, the problem was the type of the column:

full.shp$konf1900char <- as.character(full.shp$konf1900)
tm_shape(full.shp) + tm_fill(col="konf1900char")

It needs to be converted to characters with as.character. Also, it is important that there are no NA values, they can be converted to white (#ffffff in hex format):

full.shp$konf1900char[is.na(full.shp$konf1900char)] <- "#ffffff"

with these transformations, it works nicely with tmap and tm_fill takes the color values from the variable.

edit:
this is the resulting image (compare to screenshot in the question above): enter image description here

Mario
  • 2,393
  • 2
  • 17
  • 37
2
library(tmap)

#Load in some example data
data(Europe)

#Create a dataframe with all a column containing country ID and another with an assigned color:
region_col <- data.frame(
  iso_a3 = Europe$iso_a3,
  mycolors = c(rep("#94b8b8",68)), #Assign the same color to all regions initilally
  stringsAsFactors = FALSE
)

#Highlight some selected regions by looking up the 3 letter iso_a3 code and changing the 
#associated hexidecimal color reference:
region_col$mycolors[region_col$iso_a3 == "GBR"] <- "#00ff00"
region_col$mycolors[region_col$iso_a3 == "FRA"] <- "#ff0000"
region_col$mycolors[region_col$iso_a3 == "DEU"] <- "#ffff00"
region_col$mycolors[region_col$iso_a3 == "ESP"] <- "#0000ff"

#Import color selection from region_col dataframe into Europe SpatialPolygonDataFrame
Europe$color <- region_col$mycolors

#Plot resultant map:
qtm(Europe, fill = "color")

enter image description here

Graeme
  • 363
  • 1
  • 9