[R] help on plots
Marc Schwartz (via MN)
mschwartz at mn.rr.com
Thu Sep 28 23:36:09 CEST 2006
On Thu, 2006-09-28 at 23:55 +0800, zhijie zhang wrote:
> Dear friends,
> I met a problem on plotting.
> My dataset is :
> year MHBC LHBC MHRC LURC
> 1993 11.75 4.50 0.43 0.46
> 1994 7.25 1.25 0.35 0.51
> 1995 8.67 2.17 0.54 0.44
> 1996 2.67 1.33 0.78 0.47
> 1997 3.42 4.92 0.69 0.48
> 1998 1.92 3.08 0.72 0.54
> 1999 2.33 2.58 0.74 0.41
> 2000 5.75 4.50 0.45 0.50
> 2001 3.75 4.42 0.52 0.47
> 2002 2.33 1.83 0.58 0.45
> 2003 0.25 2.83 0.50 0.39
> I want to get a plot -line with scatters, the requirement is :
> x-axis is year;
> two y-axis:
> y1 corresponds to MHBC and LHBC;
> y2 corresponds to MHRC and LURC;
> hope to use different symbols to differentiate the MHBC,LHBC,MHRC and LURC.
>
> The following is my program, but very bad ,:
> *plot(a$year,a$MHBC,type='b') #line1
> par(new=T)
> plot(a$year,a$LHBC,type='b') #line2
> par(new=T)
> plot(a$year,a$MHRC,type='b') #line3
> par(new=T)
> plot(a$year,a$LURC,type='b') #line4
> axis(4, at=pretty(range(a$MHRC)))*
> In the figure, the labels and scales of X-axis are vague, the scale of
> y-axis is not very good.
> The better figure should be like the line1 and 2 are in the upper, and line3
> and 4 are in the bottom.
> Any suggestion are welcome!
It's not entirely clear to me what you want, so let me offer three
possibilities.
1. Do all four lines in a single plot with a common y axis:
matplot(a$year, a[, -1], type = "o", pch = 15:18)
2. Do all four lines in a single plot with the first two having a
separate left hand y axis and the second two having a separate right
hand y axis:
# Draw the first pair of lines
matplot(a$year, a[, 2:3], type = "o", pch = c(19, 20),
lty = "solid", ann = FALSE)
# Get the current plot region boundaries
usr <- par("usr")
# Get the range of the second set of columns
range.y2 <- range(a[, 4:5])
# Change the plot region y axis range for the second
# set of columns. Extend them by 4% as per the default
par(usr = c(usr[1], usr[2],
range.y2[1] * 0.96 , range.y2[2] * 1.04))
# Add the second pair of lines
matlines(a$year, a[, 4:5], type = "o", pch = c(15, 18),
lty = "dashed", col = c("blue", "green"))
# Add the second y axis
axis(4)
3. Do the first two lines in an upper plot and the second two lines in a
lower plot, each has its own y axis range:
# Set plot region to have two rows
par(mfrow = c(2, 1))
# Adjust the plot margins
par(mar = c(2, 5, 2, 2))
# Draw the first pair of lines
matplot(a$year, a[, 2:3], type = "o", pch = c(19, 20),
lty = "solid", ylab = "First Pair")
par(mar = c(3, 5, 2, 2))
# Add the second pair of lines
matplot(a$year, a[, 4:5], type = "o", pch = c(15, 18),
lty = "dashed", col = c("blue", "green"),
ylab = "Second Pair")
See ?matplot, ?par and ?points for more information.
HTH,
Marc Schwartz
More information about the R-help
mailing list