2
votes

I'm trying to create a barplot combined with line plots, but I have troubles centering all graphs, so it match the x-axis. I want the bar labels (had to censor them ;) ) and points of both line plots centered with the x-axis ticks.

I don't really get why the x-axis ticks are correctly centered with bars, but everything else is dis-centered in such strange way (although I'm using the same variable x to position both of them).

How can I center them all together.

Here is the code that I have made for plotting (the image it produces is below):

#### base sytem
par(mar = rep(4, 4))
barData <- con
y <- lineData <- CPL
z <- CPLmax
x <- barplot(barData, 
             axes = FALSE,
             col = "green", 
             xlab = "",
             ylab = "",
             ylim = c(0, max(con) * 1.1))
axis(1, at = x, labels = timeline)
axis(4, at = NULL)
par(new = TRUE)
plot(x = x, y = y, type = "b", col = "blue", axes = FALSE, xlab = "", ylab = "", ylim = c(0, max(CPL) * 1.1))
lines(x = x, y = z, type = "b", col = "red",  axes = FALSE, ylab = "", ylim = c(0, max(CPL) * 1.1))
axis(2, at = NULL)
text(x = x, y = 3, labels = barData, pos = 1 )
abline(v= x, col="purple")
print(x)
print(y)
box()

enter image description here

2

2 Answers

3
votes

As an alternative to @JTT's answer - you could fix the xlim params like this:

con <- setNames(runif(12), seq(as.Date("2014-01-01"), as.Date("2014-12-31"), "month"))
xlim <- c(0, length(con)*1.25)
x <- barplot(con, col = "green", xlab = "", ylab = "", ylim = c(0, max(con) * 1.1), axes = FALSE, xlim = xlim)
par(new = TRUE)
plot(x = x, type = "b", y = runif(12), xlim = xlim, xlab = "", ylab = "", axes = FALSE)
abline(v = x, col = "red")
0
votes

You are resetting the coordinate system of the plot when you call par(new=TRUE). This misaligns the new added elements when drawn over the existing barplot. Omit the par(), and instead of plot() just after that, use lines() as you do on the next line.

As an example, instead of this:

d<-1:10
x<-barplot(d)
y<-d+rnorm(10)
par(new=TRUE)
plot(x, y, type="b")

rather do this:

d<-1:10
x<-barplot(d)
y<-d+rnorm(10)
lines(x, y, type="b")

Or, if different axes for different elements on the plot are needed, you might consider setting the x-axis range explicitly, e.g.:

d<-1:10
x<-barplot(d, xlim=c(0,12))
y<-d+rnorm(10)
par(new=TRUE)
plot(x, y, type="b", xlim=c(0,12))