[R] Scaling in plot function

Marc Schwartz MSchwartz at mn.rr.com
Sun Mar 12 04:32:23 CET 2006


On Sun, 2006-03-12 at 00:09 +0100, Prasanna BALAPRAKASH wrote: 
> Dear R helpers,
> 
> I have a vector of 500 numbers and I need to plot them in such a way  
> that the first 250 values should occupy 80% of the plot and the  
> remaining ones should take 20%. More precisely, x axis ranges form  
> 1:500 and the idea is to give the snapshot of the first 250 values. I  
> tried  "axis()" and log="x", but I am not getting the required output.
> 
> 
> Thanks
> Prasanna


There may be an easier way to do this, but here are two approaches that
come to mind.  The first does this in a single plot region, the second
uses layout() to allocate space within the plot region 80/20 to two
separate plots.


1. First approach using a single plot region

# Create an initial set of 250 x vals
# from 0 to 0.8
x250.8 <- seq(0, 0.8, length = 250)

# Create a second set of 250 from 0.8 to 1.0
x250.2 <- seq(0.8, 1, length = 250)

# Concatenate the two vectors to form
# the 500 x axis vals
x.axis <- c(x250.8, x250.2)


# Now do the plot, using the 500 vals
# for the x axis values
# Draw 1st 250 with red
# Draw second 250 with green
plot(x.axis, rnorm(500), pch = 20, 
     col = c(rep("red", 250), rep("green", 250)),
     xaxt= "n")


# Now set up x axis labels from 0 to 250
# by 50 and then at 500
axis(1, at = c(seq(0, 0.8, length = 6), 1), 
     labels = c(seq(0, 250, 50), 500))


See ?seq and ?plot.default for more information.



2. Second approach using layout()

# Set a matrix of 2 cols
# Allocate 80% to 1 and 20% to 2
layout(matrix(1:2, ncol = 2), c(4, 1))

# Set margins to adjust distance
# between plots
par(mar = c(5, 2, 3, 1))

# Do plot of 1st 250 in red
# set ylim to match for both plots
# Set xlab so no output
plot(rnorm(250), ylim = c(-4, 4),
     pch = 20, col = "red", xlab = "")

# Set margins to adjust distance
# between plots
par(mar = c(5, 1, 3, 2))

# Do 2nd 250 in green
# Set xaxt so x axis is not drawn
# Set xlab so no output
plot(rnorm(250), ylim = c(-4, 4), yaxt = "n",
     pch = 20, xaxt = "n", col = "green", xlab = "")

# Now do x axis
axis(1, at = c(0, 250), labels = c(250, 500))

# Now add y axis on right plot
axis(4)

# Set outer margins for common labels
par(oma = c(3, 0, 3, 0))

# Do title
mtext(side = 3, "Example of using layout()", outer = TRUE,
      line = 1, cex = 1.5)

# Do common x axis label
mtext(side = 1, "Index", outer = TRUE,
      line = 1, cex = 1)


See ?layout, ?mtext and ?par for more information.


I think that in general, I would recommend the second approach, since it
emphasizes the separation between the two sets of 250. However, it may
be dependent upon your actual data.

HTH,

Marc Schwartz




More information about the R-help mailing list