Is it possible to create a combined column graph and line graph with different Y axis like you can in Excel? I want to automate the production of graphs where the line graph is the Good -Bad ratio and the bar graph is the percent of universe for the given interval of another variable. The left Y axis would be for the Good - Bad ratio and the right Y axis would be the percent of universe. I'd like to do this with lattice but any recommendations would be apprec开发者_开发知识库iated.
require(plotrix) # followed by a slight variation of the first example of twoord.plot
twoord.plot(2:10,seq(3,7,by=0.5)+rnorm(9), type=c("bar", "l"),
1:15,rev(60:74)+rnorm(15),xlab="Sequence",
ylab="Ascending values",rylab="Descending values",
main="Plot with two ordinates - points and lines")
There seems to be a problem with the comment formatting so I am putting the code here as well. The rx and lx vectors need to be numeric but the xticklab argument can be used to label correctly:
twoord.plot(lx=1:10, ly= df$Pct, rx=1:10, ry= df$Rate, type=c('bar','l'),
xticklab=df$Segment, xlab='Segment', ylab='Percent of Good', rylab='Good Rate')
I know this question already has an accepted answer, but I just wanted to add another option. If you find yourself in a situation where your options beyond "base" R are limited (eg if you are working on a disparate team of people and need highest possible code compatibility, a situation I've found myself in recently), you can always use the
par(new=TRUE)
command to plot one plot on top of another -- so, a barplot and a line plot. The trick here (thanks to this post) is to use "plot" for both the line and bar charts, just use "type='h'" and the "lend" and "lwd" options to create a barplot from the line plot.
This replicates the code above, using only the "base" functions:
## Set up data
line.x <- 2:10
bar.x <- 2:10
bar.y <- seq(3,7,by=0.5)+rnorm(9)
bar.x <- 1:15
bar.x <- 2:10
line.x <- 1:15
line.y <- rev(60:74)+rnorm(15)
x.range <- range(bar.x, line.x)
## Plot the data
par(mar=c(5,4,4,4)+0.1) ## Make enough room for both labels
plot(y=bar.y, x=bar.x, type='h', lwd=25, lend=4, xlim=x.range, xlab="Sequence", ylab="", main="Plot with two ordinates - points and lines")
par(new=TRUE)
plot(y=line.y, x=line.x, col='red', type='l', xlim=x.range, axes=FALSE, xlab='', ylab='')
## Set up the axes and labels
axis(side=4, col='red', labels=FALSE)
at = axTicks(4)
mtext(side = 4, text = at, at = at, col = "red", line = 1)
## Add x-axis labels; this allows customization of the how far out labels are
mtext(text='Descending values', side=4, line=2, col='red')
mtext(text='Ascending values', side=2, line=2)
If you want to do this by hand, look at the updateusr function in the TeachingDemos package.
This only works with base graphics, not lattice.
精彩评论