5

I currently have a shapefile of the UK and have plot the population of species in different regions of the UK. So far I have just plotted 3 levels of species population and coloured them red=high, orange=med, green=low. But what I would like to do would be to have a gradient plot instead of being bounded by just 3 colours. So far I have a table called Count that has the regions as the column names and then the count of species for each region below. My lowest count being 0 and my highest being around 2500 and the regions in Count match with the regions in my shapefile. I have a function that determines what is high, med, low based on levels you input yourself

    High<-colnames(Count)[which(Count>'input value here')]

and then these are plotted onto the shapefile like this:

    plot(ukmap[(ukmap$Region %in% High),],col='red',add=T)

Unfortunately I can't really install any packages, I was thinking of using colorRamp, but I'm not really sure what to do?

EDIT: my data looks something like this

      Wales   Midlands North Scotland South East South West
 1        551       32      124        1         49         28
 3         23       99      291      152        164        107
 4          1        7       17       11         21         14
 7        192       32       12        0          1          9
 9         98       97        5        1         21          0

and the first column is just a number that represents the species and currently I have a function that plots the count onto a UK shapefile but based on boundaries of high, med and low. The data above is not attached to my shapefile. I then loop through for each line (species) of my data set and plot a new map for each line (species).

userk
  • 811
  • 5
  • 11
  • 19

3 Answers3

7

All right, I'll bite. I'm not going to use base R because plot is too hard for me to understand, so instead we will be using ggplot2.

# UK shapefile found via http://www.gadm.org/download
uk.url <- "http://www.filefactory.com/file/s3dz3jt3vr/n/GBR_adm_zip"

# replace following with your working directory - no trailing slash
work.dir <- "C:/Temp/r.temp/gb_map"

# the full file path for storing file
file.loc <- paste0(work.dir, "/uk.zip")

download.file (uk.url, destfile = file.loc, mode = "wb")
unzip(file.loc, exdir = work.dir)

# open the shapefile
require(rgdal)
require(ggplot2)
uk <- readOGR(work.dir, layer = "GBR_adm2")

# use the NAME_2 field (representing counties) to create data frame
uk.map <- fortify(uk, region = "NAME_2")

# create fake count data...
uk.map$count <- round(runif(nrow(uk.map), 0, 2500), 0)

# quick visual check
ggplot(uk.map, aes(x = long, y = lat, group = group, fill = count)) +
    geom_polygon(colour = "black", size = 0.5, aes(group = group)) +
    theme()

This generates the output below, which may be similar to what you need.

screenshot

Note that we don't explictly specify the gradient in this case - we just leave it up to ggplot. If you wish to specify those details it is possible but more involved. If you go down that route you should create another column in uk.map to allocate each count into one of (say) 10 bins using the cut function. The uk.map data frame looks like this:

> str(uk.map)
'data.frame':   427339 obs. of  8 variables:
 $ long : num  -2.05 -2.05 -2.05 -2.05 -2.05 ...
 $ lat  : num  57.2 57.2 57.2 57.2 57.2 ...
 $ order: int  1 2 3 4 5 6 7 8 9 10 ...
 $ hole : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ piece: Factor w/ 234 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ group: Factor w/ 1136 levels "Aberdeen.1","Aberdeenshire.1",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ id   : chr  "Aberdeen" "Aberdeen" "Aberdeen" "Aberdeen" ...
 $ count: num  1549 1375 433 427 1282 ...
> 
SlowLearner
  • 7,485
  • 9
  • 41
  • 76
  • thank you for your help, unfortunately as I said in my question I can't install any packages, but I'm sure this will be of use to others in a similar situation! – userk Aug 05 '13 at 10:05
  • You have neither `ggplot2` nor the `maps` packages? Have you done a `library()` call to check? – SlowLearner Aug 05 '13 at 11:18
  • I don't have ggplot2, I have gplots however I don't have perl installed. for drawing maps I am using maptools but yes I also have the maps package and for reading in my data from an excel spreadsheet I am using XLConnect. – userk Aug 05 '13 at 11:30
  • I'm surprised you don't have access to `ggplot2` - it's almost an integral part of R these days. Over the long term it would be beneficial to learn and use it; I suggest you ask whoever controls your R installations to give you permission. Do `?install.packages` for details. – SlowLearner Aug 07 '13 at 07:17
4

OK, here is an alternative solution that doesn't use ggplot (I will leave the ggplot solution for reference). This code is simple but it should be enough to give you some ideas as to how you can adapt it to your own data.

# UK shapefile found via http://www.gadm.org/download
uk.url <- "http://www.filefactory.com/file/s3dz3jt3vr/n/GBR_adm_zip"

# replace following with your working directory - no trailing slash
work.dir <- "C:/Temp/r.temp/gb_map"

# the full file path for storing file
file.loc <- paste0(work.dir, "/uk.zip")

download.file (uk.url, destfile = file.loc, mode = "wb")
unzip(file.loc, exdir = work.dir)

# open the shapefile
require(rgdal)
uk <- readOGR(work.dir, layer = "GBR_adm2")

# make some fake data to plot
uk@data$count <- round(runif(nrow(uk@data), 0, 2500), 0)
uk@data$count <- as.numeric(uk@data$count)

# and plot it
plot(uk, col = gray(uk@data$count/2500))

The result of the code is the following plot.

screenshot

EDIT following a request to include a legend, I have tweaked the code a little but in all honesty I don't understand base R's legend function well enough to get something of production quality and I have no wish to research it further. (Incidentally hat tip to this question for ideas.) A look at the plot beneath the code suggests that we need to reorder the legend colours etc but I will leave that to the original poster as an exercise or to post as another question.

# UK shapefile found via http://www.gadm.org/download
uk.url <- "http://www.filefactory.com/file/s3dz3jt3vr/n/GBR_adm_zip"

# replace following with your working directory - no trailing slash
work.dir <- "C:/Temp/r.temp/gb_map"

# the full file path for storing file
file.loc <- paste0(work.dir, "/uk.zip")

download.file (uk.url, destfile = file.loc, mode = "wb")
unzip(file.loc, exdir = work.dir)

# open the shapefile
require(rgdal)
uk <- readOGR(work.dir, layer = "GBR_adm2")

# make some fake data to plot
uk@data$count <- as.numeric(round(runif(nrow(uk@data), 0, 2500), 0))
uk@data$bin <- cut(uk@data$count, seq(0, 2500, by = 250), 
      include.lowest = TRUE, dig.lab = 4)

# labels for the legend
lev = levels(uk@data$bin)
lev2 <- gsub("\\,", " to ", lev)
lev3 <- gsub("\\]$", "", lev2)
lev4 <- gsub("\\(|\\)", " ", lev3)
lev5 <- gsub("^\\[", " ", lev4)
my.levels <- lev5

# Create a function to generate a continuous color palette
rbPal <- colorRampPalette(c('red','blue'))
uk@data$Col <- rbPal(10)[as.numeric(cut(uk@data$count, seq(0, 2500, by = 250)))]

# Plot
plot(uk, col = uk@data$Col)
legend("topleft", fill = uk@data$Col, legend = my.levels, col = uk@data$Col)

screenshot

Community
  • 1
  • 1
SlowLearner
  • 7,485
  • 9
  • 41
  • 76
1

Have you tried colorRampPalette?

Here is how you could try to build a gradient palette

       gradient_color <- colorRampPalette(c("blue", "red"))
       gradient_color(10)

[1] "#0000FF" "#1C00E2" "#3800C6" "#5500AA" "#71008D" "#8D0071" "#AA0055" [8] "#C60038" "#E2001C" "#FF0000"

An example plot

     plot(rep(1,10),col=gradient_color(10))
user2510479
  • 1,317
  • 11
  • 14
  • Yes I was thinking of using colorRampPalette, something along the lines of gradient_color – userk Aug 02 '13 at 14:52
  • 1
    Well, you haven't given us a reproducible question ([see here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for details) so it's difficult to help. Having said that, putting a shapefile into a question is typically not easy to do (though you could supply a download link), but at least show us what your data looks like, then we might be able to help. – SlowLearner Aug 02 '13 at 17:44