代码之家  ›  专栏  ›  技术社区  ›  ESL

如何添加Y轴和次轴X与几何线()相同的水平几何列()?

  •  0
  • ESL  · 技术社区  · 5 年前

    我有两种数据要与ggplot()合并:

    • geom_lines() 测试中持续时间与迭代的比较。
    • 其次,是一种直方图 geom_col()

    我可以把它画在一起,但在柱状图中,列的位置与持续时间轴没有关系,因为它是翻转的:

    What I get

    我想要的是,画水平线,每个线的位置与Y轴(持续时间)对齐。我不知道如何进行,也许是格罗布和次轴的组合,但我不知道如何进行。像这样: What I want

        # 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))
    
    0 回复  |  直到 5 年前