1
votes

I try to use base R to plot a time series as a bar plot and as ordinary line plot. I try to write a flexible function to draw such a plot and would like to draw the plots without axes and then add universal axis manually.

Now, I hampered by strange problem: same ylim values result into different axes. Consider the following example:

data(presidents)
# shorten this series a bit
pw <- window(presidents,start=c(1965))
barplot(t(pw),ylim = c(0,80))
par(new=T)
plot(pw,ylim = c(0,80),col="blue",lwd=3)

I intentionally plot y-axes coming from both plots here to show it's not the same. I know I can achieve the intended result by plotting a bar plot first and then add lines using x and y args of lines.

But the I am looking for flexible solution that let's you add lines to barplots like you add lines to points or other line plots. So is there a way to make sure y-axes are the same?

EDIT: also adding the usr parameter to par doesn't help me here.

par(new=T,usr = par("usr"))

enter image description here

1

1 Answers

3
votes

Add yaxs="i" to your lineplot. Like this:

plot(pw,ylim = c(0,80),col="blue",lwd=3, yaxs="i")

R start barplots at y=0, while line plots won't. This is to make sure that you see a line if it happens that your data is y=0, otherwise it aligns with the x axis line.