如何根据时钟值对齐geom_text

时间:2016-10-17 10:14:51

标签: r ggplot2 text-alignment geom-text

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

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

图我想要复制:

figure i want to replicate

我的数字:

my figure

按照我的绘图代码:

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()

1 个答案:

答案 0 :(得分:0)

如果您指定了时钟值,则可以轻松计算方向,从而计算出您想要在每个方向上轻推的数量:

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())