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?
 # Give some room for the second y-axis
 # Work out the x-limits of the graph
 # Work out the x-location of the bar centres/points
 # 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
 # Add the line graph
 plot(x, y2, axes=F, type="b", xlim, ann=F,pch=20)
 # Add the second y axis
 # Add the second y label
 mtext("y2", side=4, line=3)

enter image description here

Read more here: Source link