0

Let's say I want to plot the World map with countries colored by population estimate, but I want the color ramp to start and stop at specified values (for instance, maybe I want to use one legend for several maps).

library(tmap)
data(World)

# custom color ramp
colorRamp <- colorRampPalette(c('blue', 'yellow', 'red'))

# I can plot the full range of values with my custom palette
tm_shape(World) + tm_fill('pop_est', palette = colorRamp(100))

Now let's say I want to specify custom lower and upper bounds:

customRange <- c(200, 700)

breaks <- seq(from = customRange[1], to = customRange[2], length.out = 100)

tm_shape(World) + tm_fill('pop_est', palette = colorRamp(100), breaks = breaks)

enter image description here

This clearly didn't work, and the legend also has problems. I get the following warnings:

Warning messages:
1: Values have found that are less than the lowest break 
2: Values have found that are higher than the highest break 

Any suggestions as to the proper way to do this? Thanks!

EDIT:

Further elaboration: In this example, the data I am plotting ranges from ~ 140 million to 1.4 billion. But let's say I have a 2nd map that ranges from 500 million to 5 billion. If I want the two maps to have the same color scheme, and have a single legend for both, then I would want the color palette for BOTH maps to span 140 million to 5 billion.

So, how can I specify the min and max value that the color palette will span?

Pascal
  • 1,590
  • 2
  • 16
  • 35

1 Answers1

0

Founded the solution here: How to adjust color palette with customized breaks in tmap?

Populations are in millions and you should also define less breaks.

map <- tm_shape(World[World$continent == "North America",]) + 
  tm_fill('pop_est', 
          breaks = c(0, 100000000, 200000000, 300000000, 400000000),
          style = "fixed",
          palette = "Reds")
map

enter image description here

map <- tm_shape(World[World$continent == "South America",]) + 
  tm_fill('pop_est', 
          breaks = c(0, 100000000, 200000000, 300000000, 400000000),
          style = "fixed",
          palette = "Reds")
map

enter image description here

Regards,

barboulotte
  • 395
  • 2
  • 8
  • What I mean is: What if I want the color palette to map to values that might be outside of what is present in the current map. I'll add additional explanation to my post. – Pascal Mar 10 '21 at 23:11
  • Thank you, your response actually made me realize that I was in fact not really doing anything wrong. The scale of that population variable and the tmap legend just threw me off. It makes sense for my map to be solid red because just about everywhere has a population of > 700. – Pascal Mar 11 '21 at 23:30
  • Thank you for the bounty. Yes it was only a problem of range. – barboulotte Mar 22 '21 at 17:42