我有两种数据要与 ggplot() 合并:
- 主要是测试中的两个
geom_lines()
持续时间与迭代。 - 次要的,是一种直方图
geom_col()
:计数与持续时间。
我可以将它绘制在一起,但在直方图中,cols 的位置与持续时间轴无关,因为它被翻转了:
我想要的是水平绘制列,以使每个列的位置与 Y 轴(持续时间)对齐。我不确定如何进行,可能是 grobs 和辅助轴的组合,但我不知道如何进行。像这样的东西:
此示例的数据、比例操作和绘图代码为:
# TEST DATA:
tests <-
data.frame(iteration=1:20,
testA=c(0.7399, 0.8103, 0.6779, 0.6608, 0.6755, 0.6842, 0.8423, 0.647,
0.6955, 0.6673, 0.6549, 0.6886, 0.6667, 0.6888, 0.7627, 0.68,
0.6588, 0.678, 0.6816, 0.6811),
testB=c(0.6185, 0.3757, 0.3633, 0.3532, 0.3517, 0.3611, 0.3487, 0.357,
0.3608, 0.3647, 0.3501, 0.3451, 0.361, 0.379, 0.3841, 0.3703,
0.3595, 0.3463, 0.4046, 0.3462))
htestA <- data.frame(
duration = c(0.749, 0.8009, 0.8528, 0.9048, 0.9567, 1.0086, 1.0605, 1.1124,
1.1643, 1.2162, 1.2681, 1.32, 1.372, 1.4239, 1.4758, 1.5277,
1.5796, 1.6315, 1.6834, 1.7353),
count = c(0, 0, 0, 1, 2, 3, 1, 6, 2, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0)
)
htestB <- data.frame(
duration = c(0.4342, 0.4934, 0.5526, 0.6118, 0.671, 0.7302, 0.7894, 0.8486,
0.9078, 0.967, 1.0261, 1.0853, 1.1445, 1.2037, 1.2629, 1.3221,
1.3813, 1.4405, 1.4997, 1.5589),
count = c(0, 0, 0, 0, 0, 0, 5, 4, 3, 2, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0)
)
# SCALE TO FLIPPED AXIS (histogram duration as X and count Y)
library(dplyr)
maxY <- max(tests$testA,tests$testB)
minD <- min(htestA$duration,htestB$duration)
maxD <- max(htestA$duration,htestB$duration)
maxC <- max(htestA$count,htestB$count)
d2x <- function(d) {(d-minD)*(max(tests$iteration)-min(tests$iteration))/(maxD-minD)+min(tests$iteration)}
c2y <- function(c) {c*maxY/maxC}
hA <- mutate(htestA,duration=d2x(duration),count=c2y(count))
hB <- mutate(htestB,duration=d2x(duration),count=c2y(count))
# PLOT
library(ggplot2)
ggplot(tests,aes(x=iteration)) +
geom_col(data=hA,aes(duration,count),fill="orange",alpha=0.3) +
geom_col(data=hB,aes(duration,count),fill="gray",alpha=0.3) +
geom_line(aes(y=testA),color="red") +
geom_line(aes(y=testB))