问题
I am trying to view this file(unsigned character, pixel =1440 and lines=720) as a map. I tried the piece of code given bellow. First, I downloaded may problem is that this code is using a continuous colour scheme, even though I have discrete data (which is a classification scheme). How can I map numbers to colours ? Please example of a wanted scale is shown below:
conne <- file("C:\\landcover.bin", "rb")
dfr<- readBin(conne, integer(), size=1,  n=720*1440, signed=F)
y<-matrix((data=dfr), ncol=1440, nrow=720)
image(y)
    回答1:
The raster package provides a method to use categorical
data. Read the help page of ratify for details.
First let's create a RasterLayer with your data:
library(raster)
dfr <- readBin('biome1440s.bin', integer(), size=1,  n=720*1440, signed=F)
r <- raster(nrow=720, ncol=1440)
r[] <- dfr
Now we define this RasterLayer as a factor with ratify. You
should change its levels using your information instead of LETTERS:
r <- ratify(r)
rat <- levels(r)[[1]]
rat$soil <- LETTERS[1:15]
levels(r) <- rat
And finally, this categorical RasterLayer can be displayed with
the levelplot method of the rasterVis package.
library(rasterVis) 
myPal <- c('lightblue', terrain.colors(14))
## using par.settings
levelplot(r, par.settings=rasterTheme(region=myPal))
## or with col.regions
levelplot(r, col.regions=myPal)
Edited: levelplot uses lattice graphics, while plot uses
base graphics. They cannot be used together (unless you use the
gridBase package). However, you can easily overlay additional
information using the +.trellis and layer functions from the
latticeExtra package. Since wrld_simpl is a
SpatialPolygonsDataFrame you can use the sp.polygons function
from the sp package to plot it.
library(maptools) ## needed for wrld_simpl
data(wrld_simpl) ## a SpatialPolygonsDataFrame
levelplot(r, col.regions=myPal) +
    layer(sp.polygons(wrld_simpl, lwd=0.5))
    回答2:
First of all, no code can use "continuous" color schemes, because all data are digital and quantized.
Now,  there are lots of built-in color patterns in R .  See ?image for a discussion of some of the common palettes used for maps and the like.  If your map data has discrete ranges of numerical values for the various soil types, a little scaling math will let you apply different colors to each category.
回答3:
Or you could use the excellent ggplot2 package. This has the geom_raster geometry which should work just fine with your data. Note that ggplot2 requires its data to be in a different format than a matrix, you can use melt from the reshape2 package to perform this conversion. See also my answer to an earlier question, which has a lot of similarities with you own.
来源:https://stackoverflow.com/questions/16213856/how-to-map-numbers-to-colours