gpt4 book ai didi

R - 绘制两个 y 轴,条形和点未对齐

转载 作者:行者123 更新时间:2023-12-04 03:16:34 25 4
gpt4 key购买 nike

对于客户,我正在尝试使用两个 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)

enter image description here

我在这里找到了一些关于双轴的灵感:http://robjhyndman.com/hyndsight/r-graph-with-two-y-axes/

我该怎么做才能使条形的中间与线图的点对齐?

最佳答案

您遇到的问题是在条形图之后调用第二个 plot 函数。这是移动/调整绘图 Canvas 的大小,这会导致后续点发生移动。

这是一个快速解决方法,它只是将点和线重新缩放到条形图上。它将条形图保存为一个对象,该对象存储条形中点的 x 轴位置。然后,当您使用“bp”作为 x 轴变量绘制 abline、线和点时,它们将正确对齐。

ymax <- max(df$counts, na.rm = TRUE) * 1.05

par(mar=c(4.1,5.1,2.1,5.1))
bp <- barplot(df$runtime, col = "palegreen2", border = "NA", ylab = "runtime in [%]",
ylim = c(0,100), font.lab = 2, xlim=c(0.2,12), )

barplot(df$runtime, col = "palegreen2", ylab = "runtime in [%]", border="NA",
ylim = c(0,100), font.lab = 2)

abline(v = bp, col = "red", lwd = 2.5)
lines(bp, df$counts/ymax*100, col = "blue", lwd = 2)
points(bp, df$counts/ymax*100, pch = 19, cex = 1.5)
axis(4,at=c(0,20,40,60,80,100), labels=c("0","100","200","300","400","500"))
mtext("Number of switching operations", side = 4, line = 3, font = 2)
axis(1, at=bp, labels=df$date)

enter image description here

关于R - 绘制两个 y 轴,条形和点未对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40466203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com