首页 文章

以编程方式定位ggplot标签

提问于
浏览
0

我正在使用ggplot2在R中以编程方式创建大量图表,除了条形标签的位置外,所有内容都能正常工作 .

这需要输入绘图高度,y轴刻度和文本大小 .

Example (stripped down) plot code:

testInput <- data.frame("xAxis" = c("first", "second", "third"), "yAxis" = c(20, 200, 60))

# Changeable variables
yMax <- 220
plotHeight <- 5
textSize <- 4

# Set up labels
geomTextList <- {
  textHeightRatio <- textSize / height
  maxHeightRatio <- yMax / height

  values <- testInput[["yAxis"]]

  ### THIS IS THE FORMULA NEEDING UPDATING
  testInput[["labelPositions"]] <- values + 5 # # Should instead be a formula eg. (x * height) + (y * textSize) + (z * yMax)?    
  list(
    ggplot2::geom_text(data = testInput, ggplot2::aes_string(x = "xAxis", y = "labelPositions", label = "yAxis"), hjust = 0.5, size = textSize)
  )
}

# Create plot
outputPlot <- ggplot2::ggplot(testInput) +
  ggplot2::geom_bar(data = testInput, ggplot2::aes_string(x = "xAxis", y = "yAxis"), stat = "identity", position = "dodge", width = 0.5) +
  geomTextList +
  ggplot2::scale_y_continuous(breaks = seq(0, yMax, yInterval), limits = c(0, yMax))

ggplot2::ggsave(filename = "test.png", plot = outputPlot, width = 4, height = plotHeight, device = "png")

我已经尝试了公式的各种系数组合,但怀疑在其中一个因素不是线性的 . 如果这纯粹是一个统计问题,我可以把它用于交叉验证,但我想知道是否有人已经解决了这个问题?

1 回答

  • 1

    如果您的问题是在处理不同的文本大小时将文本偏移到不与条重叠,只需使用已经与文本大小成比例的 vjust . 值 0 将使文本的底部触摸条形图,一个小的负值将使它们之间有一些空格:

    testInput <- data.frame("xAxis" = c("first", "second", "third"), "yAxis" = c(20, 200, 60))
    
    # Changeable variables
    yMax <- 220
    plotHeight <- 5
    textSize <- 4
    
    # Set up labels
    geomTextList <- {
    
      values <- testInput[["yAxis"]]
    
      testInput[["labelPositions"]] <- values # Use the exact value
      list(
        ggplot2::geom_text(
          data = testInput,
          # vjust provides proportional offset
          ggplot2::aes_string(x = "xAxis", y = "labelPositions", label = "yAxis"),
          hjust = 0.5, vjust = -0.15,  size = textSize
        )
      )
    }
    
    # Create plot
    outputPlot <- ggplot2::ggplot(testInput) +
      ggplot2::geom_bar(data = testInput, ggplot2::aes_string(x = "xAxis", y = "yAxis"), stat = "identity", position = "dodge", width = 0.5) +
      geomTextList +
      ggplot2::scale_y_continuous(limits = c(0, yMax))
    ggplot2::ggsave(filename = "test.png", plot = outputPlot, width = 4, height = plotHeight, device = "png")
    

相关问题