【问题标题】:ggplot2: Why are my text annotations not aligned right?ggplot2:为什么我的文本注释没有对齐?
【发布时间】:2017-01-15 04:44:58
【问题描述】:

我正在尝试使用annotate 标记直线段。但是,将注释的角度设置为线的斜率不会使注释与线段对齐。

library(ggplot2)

ggplot(data.frame(x = seq(0, 14, 0.1)), aes(x = x)) + 
  stat_function(fun = function(x) {
    14 - x
  }, geom = "line") + 
  theme_bw() + 
  annotate(
    geom = "text", 
    x = 7.5, y = 7.5,
    label = "x + y = 14",
    angle = -45)  # NISTunits::NISTradianTOdeg(atan(-1))

这给出:

有人可以帮助解释这种现象,以及如何解决这个问题,即将注释对齐以与线段具有相同的角度?

【问题讨论】:

  • 因为 x 轴的长度与 y 轴的长度不同。因此,角度不是 45 !如果两个轴具有相同的比例,它将工作 100%
  • @Kabulan0lak 太好了,这是有道理的——所以建议我应该将角度乘以视口的纵横比?我怎么能以编程方式做到这一点?
  • 视图是否有固定大小?如果是这样,您可以计算轴 x 和 y 之间的比率以获得适当的角度,是的。
  • @Kabulan0lak 不,视口没有固定的纵横比。
  • 您可以添加coord_fixed() 以便固定纵横比...

标签: r ggplot2


【解决方案1】:

我相信这应该给你你想要的。请参阅此答案以供参考Get width of plot area in ggplot2

#Plot so we can reference the viewport
ggplot(data.frame(x = seq(0, 14, 0.1)), aes(x = x)) + 
  stat_function(fun = function(x) {
    14 - x
  }, geom = "line")

#Get the currentVPtree and then convert the VP's height/width to inches
current.vpTree()
a <- convertWidth(unit(1,'npc'), 'inch', TRUE)
b <- convertHeight(unit(1,'npc'), 'inch', TRUE)

#Replot using the ratio of a/b to get the appropriate angle
ggplot(data.frame(x = seq(0, 14, 0.1)), aes(x = x)) + 
  stat_function(fun = function(x) {
    14 - x
  }, geom = "line") + 
  theme_bw()+ 
  annotate(
    geom = "text", 
    x = 7.5, y = 7.5,
    label = "x + y = 14",
    angle = (atan(a/b) * 180/pi) + 270) 

我们基本上得到视口的宽度/高度,然后使用简单的几何(反正切,因为我们有三角形的两边)来计算线的实际角度是多少。

结果:

【讨论】:

  • 当尝试将文本斜率与绘图中的其他元素匹配时,添加 +coord_fixed(a/b) 以设置纵横比会很有帮助,否则文本的角度可能会改变,例如,如果将绘图导出为图片或添加/更改图例。
猜你喜欢
  • 2014-12-28
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
相关资源
最近更新 更多