我正在为客户尝试创建一个带有两个y轴的组合条形图和折线图(带有点)。问题是,我的条形图和点没有对齐。
背景:我们有几台机器,正在测量它们的开/关次数以及每台机器运行的时间。我们想要将这两个信息结合在一个图中以节省空间,因为我们有多台机器。
数据按天或小时汇总。以下是一些示例数据:
date <- seq(as.Date("2016-10-01"), as.Date("2016-10-10"), "day")
counts <- c(390, 377, 444, NA, NA, NA, NA, 162, 166, 145)
runtime <- c(56.8, 59.4, 51.0, NA, NA, NA, NA, 38.5, 40.9, 43.4)
df <- data.frame(date = date, counts = counts, runtime = runtime)
这是我到目前为止尝试的:
par(mar = c(3,4,4,4) + 0.3)
barplot(df$runtime, col = "palegreen2", border = "NA", ylab = "runtime in [%]",
ylim = c(0,100), font.lab = 2)
par(new = TRUE)
ymax <- max(df$counts, na.rm = TRUE) * 1.05
plot(df$date, df$counts, type = "n", xlab = "", ylab = "", yaxt = "n",
main = "Machine 1", ylim = c(0, ymax))
abline(v = date, col = "red", lwd = 2.5)
lines(df$date, df$counts, col = "blue", lwd = 2)
points(df$date, df$counts, pch = 19, cex = 1.5)
axis(4)
mtext("Number of switching operations", side = 4, line = 3, font = 2)
我在这里找到了关于双坐标轴的灵感: http://robjhyndman.com/hyndsight/r-graph-with-two-y-axes/
我该怎么做才能让条形图的中心与折线图的点对齐?