r – Combining bar and line plot, different y axis, without ggplot

While I agree with Gregor that ggplot with a minimal theme is likely the correct tool for this, I thought it was interesting enough give it a try with base R. It was harder than I thought it would be:

 # Define some data, two sets of values to plot
 y1 = c(10,20,30)
 y2 = c(40,60,53)
 
 # Against one group variable
 group = c("A","B","C")
 
 # How much space to leave between the bars?
 space=0.2
 
 # Give some room for the second y-axis
 par(mar=c(5,4,4,5)+.1)
 
 # Work out the x-limits of the graph
 xlim=c(0,space+(1+space)*length(group))
 
 # Work out the x-location of the bar centres/points
 x=(1+space)*seq_along(group)-0.5
 
 # Plot the bar graph
 barplot(y1, space=space, xlim=xlim,col="red", xlab="Group", ylab="y1")
 
 # Add the x=axis
 axis(1, labels=group, at=x)

 # Start a new graph without overwriting the old one
 par(new=TRUE)
 
 # Add the line graph
 plot(x, y2, axes=F, type="b", xlim, ann=F,pch=20)
 
 # Add the second y axis
 axis(4)
 
 # Add the second y label
 mtext("y2", side=4, line=3)

enter image description here

Read more here: Source link