我正在尝试创建一个结合线图的条形图,但是我将所有图形居中的麻烦,因此它与x轴相匹配。我想要条形标签(必须审查它们;))和两个线图的点以x轴刻度为中心。
我真的不明白为什么x轴刻度正确地以条形为中心,但其他一切都以这种奇怪的方式消失(尽管我使用相同的变量x来定位它们)。
我怎样才能将它们集中在一起。
这是我为绘图制作的代码(它产生的图像如下):
#### 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()
作为@ JTT答案的替代方案 - 您可以像这样修复xlim参数:
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")
当您调用par(new=TRUE)
时,您正在重置绘图的坐标系。当在现有条形图上绘制时,这会使新添加的元素错位。省略par()
,而不是之后的plot()
,使用lines()
,就像你在下一行一样。
举个例子,而不是这个:
d<-1:10
x<-barplot(d)
y<-d+rnorm(10)
par(new=TRUE)
plot(x, y, type="b")
而是这样做:
d<-1:10
x<-barplot(d)
y<-d+rnorm(10)
lines(x, y, type="b")
或者,如果需要绘图上不同元素的不同轴,则可以考虑明确设置x轴范围,例如:
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))