以编程方式定位ggplot标签

时间:2017-11-15 20:36:46

标签: r ggplot2

我正在使用ggplot2在R中以编程方式创建大量图表,除了条形标签的位置外,其他所有图表都完美无缺。

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

示例(细分)绘图代码:

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 个答案:

答案 0 :(得分: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")