【问题标题】:How to align geom_text according to clock values如何根据时钟值对齐 geom_text
【发布时间】:2017-02-26 06:44:11
【问题描述】:

希望有人可以帮助我解决这个问题。我尝试了几种解决方案,但均未成功。

我想复制下图#1。因此,我已将变量时钟(值从 1 到 12)添加到我的数据框中,以将其用作 geom_text 对齐的参数。

我要复制的图:

我的图:

按照我的代码进行绘图:

p1 <- ggplot(data, aes(x=tax, y=employment)) + geom_point(colour = ifelse(style == 1 | style == 2,"black","grey")) + geom_smooth(method=lm, se=FALSE)
p1 + coord_cartesian(xlim = c(0, 0.8), ylim = c(0.5,0.9), expand = FALSE) + labs(x = "1 - participation taxrate", y="Employment rate") + geom_text(aes(family = "Times New Roman", label=ifelse(style == 1 | style == 2 ,Country,''))) + theme_bw()

【问题讨论】:

  • 您会对更清晰的标签(即更少/没有重叠)感到满意,还是想要完全重新制作示例图?
  • @NathanDay 如果可能的话,我想根据我的时钟变量定位文本。否则,我会尝试使用 ggrepel 使其更清晰。还是您有更简单的解决方案?
  • 您可以使用 position = position_nudge() 为 x 和 y 设置适当的值。
  • 我自己会退回到ggrepel。看起来@shadow 可能会有所作为,我打算用 hjust 和 vjust 尝试同样的想法

标签: r ggplot2 text-alignment geom-text


【解决方案1】:

如果你已经指定了时钟值,你可以很容易地计算出方向以及你想要在每个方向上微调的量:

angle <- clock/12*2*pi
radius <- 0.01
ng <- data.frame(x = radius * sin(angle), 
                 y = radius * cos(angle))

然后您可以将position = position_nudge(x = ng$x, y = ng$y) 添加到geom_text 语句中。下面我还删除了您尝试复制的图中未出现的网格线。

p1 + coord_cartesian(xlim = c(0, 0.8), ylim = c(0.5,0.9), expand = FALSE) + 
  labs(x = "1 - participation taxrate", y="Employment rate") + 
  geom_text(aes(family = "Times New Roman", label=ifelse(style == 1 | style == 2 ,Country,'')), 
            position = position_nudge(x = ng$x, y = ng$y)) + 
  theme_bw() +
  theme(panel.grid.major.x = element_blank(), 
        panel.grid.minor.x = element_blank())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-25
    • 2019-09-04
    • 2022-01-06
    • 2019-04-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多