Axes at minimum extent, no padding, in plots of raster* objects

Is there a way to ensure that the box around a plot matches the raster extents exactly? In the following there is a gap above and below or to the left and right of the raster depending on the device proportions:

require(raster) r = raster() r[]= 1 plot(r, xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r)))

One element of the problem with raster objects is that asp=1 to ensure proper display. The following basic scatterplot has the same issue when asp=1:

plot(c(1:10), c(1:10), asp=1)

Try vectorplot(r) from the rasterVis package to see what I want the axes to look like.

EDIT:

Solutions need to play nice with SpatialPoints overlays, not showing points outside the specified raster limits:

require(raster) require(maptools) # Raster r = raster() r[]= 1 # Spatial points x = c(-100, 0, 100) y = c(100, 0, 100) points = SpatialPoints(data.frame(x,y)) plot(r, xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r))) plot(points, add=T)

-------------Problems Reply------------

You'd probably do best to go with one of the lattice-based functions for plotting spatial raster objects provided by the raster and rasterVis packages. You discovered one of them in vectorplot(), but spplot() or levelplot() better match your needs in this case.

(The base graphics-based plot() method for "RasterLayer" objects just doesn't allow any easy way for you to set axes with the appropriate aspect ratio. For anyone interested, I go into more detail about why that's so in a section at the bottom of the post.)

As an example of the kind of plot that levelplot() produces:

require(raster)
require(rasterVis)

## Create a raster and a SpatialPoints object.
r <- raster()
r[] <- 1:ncell(r)
SP <- spsample(Spatial(bbox=bbox(r)), 10, type="random")

## Then plot them
levelplot(r, col.regions = rev(terrain.colors(255)), cuts=254, margin=FALSE) +
layer(sp.points(SP, col = "red"))

## Or use this, which produces the same plot.
# spplot(r, scales = list(draw=TRUE),
# col.regions = rev(terrain.colors(255)), cuts=254) +
# layer(sp.points(SP, col = "red"))

Axes at minimum extent, no padding, in plots of raster* objects

Either of these methods may still plot some portion of the symbol representing points that fall just outside of the plotted raster. If you want to avoid that possibility, you can just subset your SpatialPoints object to remove any points falling outside of the raster. Here's a simple function that'll do that for you:

## A function to test whether points fall within a raster's extent
inExtent <- function(SP_obj, r_obj) {
crds <- [email protected]
ext <- extent(r_obj)
crds[,1] >= [email protected] & crds[,1] <= [email protected] &
crds[,2] >= [email protected] & crds[,2] <= [email protected]
}
## Remove any points in SP that don't fall within the extent of the raster 'r'
SP <- SP[inExtent(SP, r), ]


Additional weedy detail about why it's hard to make plot(r) produce snugly fitting axes

When plot is called on an object of type raster, the raster data is (ultimately) plotted using either rasterImage() or image(). Which path is followed depends on: (a) the type of device being plotted to; and (b) the value of the useRaster argument in the original plot() call.

In either case, the plotting region is set up in a way which produces axes that fill the plotting region, rather than in a way that gives them the appropriate aspect ratio.

Below, I show the chain of functions that's called on the way to this step, as well as the call that ultimately sets up the plotting region. In both cases, there appears to be no simple way to alter both the extent and the aspect ratio of the axes that are plotted.

  • useRaster=TRUE

    ## Chain of functions dispatched by `plot(r, useRaster=TRUE)`
    getMethod("plot", c("RasterLayer", "missing"))
    raster:::.plotraster2
    raster:::.rasterImagePlot

    ## Call within .rasterImagePlot() that sets up the plotting region
    plot(NA, NA, xlim = e[1:2], ylim = e[3:4], type = "n",
    , xaxs = "i", yaxs = "i", asp = asp, ...)

    ## Example showing why the above call produces the 'wrong' y-axis limits
    plot(c(-180,180), c(-90,90),
    xlim = c(-180,180), ylim = c(-90,90), pch = 16,
    asp = 1,
    main = "plot(r, useRaster=TRUE) -> \nincorrect y-axis limits")

  • useRaster=FALSE

    ## Chain of functions dispatched by `plot(r, useRaster=FALSE)`
    getMethod("plot", c("RasterLayer", "missing"))
    raster:::.plotraster2
    raster:::.imageplot
    image.default

    ## Call within image.default() that sets up the plotting region
    plot(NA, NA, xlim = xlim, ylim = ylim, type = "n", xaxs = xaxs,
    yaxs = yaxs, xlab = xlab, ylab = ylab, ...)

    ## Example showing that the above call produces the wrong aspect ratio
    plot(c(-180,180), c(-90,90),
    xlim = c(-180,180), ylim = c(-90,90), pch = 16,
    main = "plot(r,useRaster=FALSE) -> \nincorrect aspect ratio")

Man, I got stumped and ended up just turning the foreground color off to plot. Then you can take advantage of the fact that the raster plot method calls fields:::image.plot, which lets you just plot the legend (a second time, this time showing the ink!). This is inelegant, but worked in this case:

par("fg" = NA)
plot(r, xlim = c(xmin(r), xmax(r)), ylim = c(ymin(r), ymax(r)), axes = FALSE)
par(new = TRUE,"fg" = "black")
plot(r, xlim = c(xmin(r), xmax(r)), ylim = c(ymin(r), ymax(r)), axes = FALSE, legend.only = TRUE)
axis(1, pos = -90, xpd = TRUE)
rect(-180,-90,180,90,xpd = TRUE)
ticks <- (ymin(r):ymax(r))[(ymin(r):ymax(r)) %% 20 == 0]
segments(xmin(r),ticks,xmin(r)-5,ticks, xpd = TRUE)
text(xmin(r),ticks,ticks,xpd=TRUE,pos=2)
title("sorry, this could probably be done in some more elegant way")

Axes at minimum extent, no padding, in plots of raster* objects

Category:r Views:1 Time:2012-02-17
Tags:

Related post

  • Plotting a raster behind a shapefile 2012-02-14

    How can I plot a "raster" object behind a shapefile object? Both plot fine on their own but the points don't plot over the raster: require(rgdal) require(maptools) require(raster) myproj = "+proj=utm +zone=12 +north +ellps=WGS84 +units=m" shp = readS

  • How do I combine setting axes limits and zooming in a MATLAB plot? 2009-03-27

    Here is the basic situation in a MATLAB session >> figure >> h=axes; >> y=sin(0:2*pi/100:pi); >> plot(y); >> set(h,'xlim',[20 80]); Now I want to be able to use the figure toolbar's Zoom In/Out buttons to reset the view

  • Highcharts padding between plot and graph, how to remove? 2011-07-22

    How can i remove padding between my chart and plot. I want my chart to start from the edge of plot and end the same way, but no matter what I try, i cannot remove padding :( Thanks! --------------Solutions------------- You can do that with: plotOptio

  • use axes coordinate to generate an image without plotting it, in Matlab 2011-10-11

    I have an image full of objects of the shape of an ellipse. I need to design an ellipse for each object that is the best fit for the object itself. I have found a code that helps me to plot the ellipses on the image here. I have changed the final par

  • Adding Points, Legends and Text to plots using xts objects 2011-08-11

    I am starting on a bit of analysis on pairs of stocks (pairs trading) and here is the function I wrote for producing a graph (pairs.report - listed below). I need to plot three different lines in a single plot. The function I have listed does what I

  • Padding string to left with objective c 2009-06-08

    How can one pad a string to left in objective c. E.g if I have an integer value of 6 I want it to be displayed as 06. I use stringByPaddingToLength: but it pads it to the right like 60. Your help is much appreciated. --------------Solutions----------

  • Plotting/visualising 3D objects in Java? 2010-10-06

    I know there's Java3D, but from what I also know it's not fit for what I want to do, which is, based on a series of pictures to plot a 3D image on the screen. For instance lets say we have XX-XXXX (or more) pictures of a human face, we process them a

  • Get minimum and maximum time value from list of object property using Linq 2011-02-04

    I have settings object with property class Settings { DateTime StartTime; DateTime EndTime; } and I have created a list of this setting object. How can I get the MaxTime and MinTime from the collection of objects using LINQ? --------------Solutions--

  • MatLab: Scatter Plots and Raster Plots 2011-02-25

    Scatter Plots in MatLab. I can create a scatter plot with x and y arrays being the same size as follows: function RasterTest() clear all % clear memory clc; % clear command window close all; % close any figure windows that are open x=[1 2 3]; % x pos

  • R-project: plot 2 zoo objects (price series) that have some date mis-matches 2011-04-03

    I have 2 zoo objects - 1) Interest rate spread between 10-YR-US-Treasury and 2-YR-US-Treasury (object name = sprd) 2) S&P 500 index (object name = spy) > str(spy) ‘zoo’ series from 1976-06-01 to 2011-03-31 Data: num [1:8791] 99.8 100.2 100.1 9

  • overriding axis labels after plot in R - not working if plotting an scb object? 2011-10-02

    What should I check about the object I plot to be able to override the axis labels, which remain variable names generated be the scb call instead of my specification below? scb is in the locfit library: http://cran.r-project.org/web/packages/locfit/l

  • How to retrieve the maximum date and minimum date from Sharepoint server 2010 using client object model? 2011-12-13

    I am developing silverlight web part. I have a one List Entry log. In this list I am storing all the entries of basic information. All the entries are saved successfully. Now I want to retrieve the maximum date and minimum date on which these entries

  • What are the minimum changes necessary to port ANSI C to Objective C? 2011-08-11

    As a Mac Newbie I need to convert about 5,000 lines of ANSI C to Objective C to be used in an iPad app. Most of the code is similar to the example below. To save time and minimize bugs I want to only change the original C code when absolutely necessa

  • Changing axes and color of plots in Matlab 2010-05-06

    How do you get rid of the axes and dotted line grids when you plot in Matlab? Also, how do I make subplots of subplots. Since that's probably not very clear, what I mean is the following... Let's say I have a 10x10x10 .mat file, so I open each of the

  • How can I plot with 2 different y-axes? 2011-05-26

    I would like superimpose two scatter plots in R so that each set of points has its own (different) y-axis (i.e., in positions 2 and 4 on the figure) but the points appear superimposed on the same figure. Is it possible to do this with plot? Edit Exam

  • How to choose the numbers shown on the axes of a plot in mathemetica? 2011-08-20

    I have already checked all the examples and settings in the Mathematica documentation center, but couldn't find any example on how to choose the numbers that will be shown on the axes. How do I change plot axis numbering like 2,4,6,.. to PI,2PI,3PI,.

  • how to display only the minimum and the maximum values in a legend while using image.plot function 2012-03-09

    I am using image.plot function to display a color bar with a image. For the color bar, I wish to display the legend at its boundary positions Only. However, currently I am getting tics at various places in the middle. Moreover, the corresponding valu

  • Inner Plot Margin with Default XTS Plot 2011-10-24

    When plotting an XTS object without any custom par attributes, I get a margin within the plot box (or "plot area" going off of http://research.stowers-institute.org/efg/R/Graphics/Basics/mar-oma/index.htm): (It is hard to see due to white on white, b

  • How to move a Core Plot graph 2011-10-04

    I have a Core-Plot Graph within a Mac Application. But the inside table is appearing shifted down and to the left of the containing "frame/border" so that neither of the axis' are showing. I cannot figure out how to change this does anyone know what

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.203 (s). 11 q(s)