ggplot2修复重叠的y标签

时间:2019-02-14 11:48:24

标签: r ggplot2 label axis-labels

代码示例
让我以这个小例子为例:

example.data <- data.frame(
  x = seq(1,5),
  y = c(seq(1,3), 4.1, 4.11),
  y.label = letters[1:5]
)


library(ggplot2)
ggplot(example.data, aes(x=x, y = y)) + 
  geom_point() +
  scale_y_continuous(breaks = example.data$y, labels = example.data$y.label)

由于4.1和4.11彼此非常接近,因此标签会重叠:

enter image description here

信息
我为出版物绘制了非常相似的图形,并且不想增加图形的大小只是为了使标签合适(这将要求图形很大)。我对ggrepel很熟悉,但是据我所知,这仅适用于绘图本身中的文本注释,不适用于坐标轴。

问题
如何确保标签不重叠而不必增加整个图的大小?

2 个答案:

答案 0 :(得分:1)

我宁愿这样。绘制一个法线图和第二个放大图。然后使用this solution覆盖它们。

p1 <- ggplot(example.data, aes(x=x, y = y)) + 
  geom_point() + 
  scale_y_continuous(breaks = example.data$y[1:4], labels = example.data$y.label[1:4])

p2 <- ggplot(example.data, aes(x=x, y = y)) + 
  geom_point() + 
  xlim(3.9, 5.1) + 
  scale_y_continuous(breaks=seq(4.100, 4.111, .002), labels=c("d", rep("", 4), "e"),
                     limits=c(4.1, 4.111))

vp <- grid::viewport(width=0.4, height=0.15, x=.8, y=.4)

png("plot.png")
print(p1)
print(p2, vp=vp)
dev.off()

结果

enter image description here

通过阅读指南,它变得更加清晰:

library("ggforce")
p1 <- p1 + geom_circle(aes(x0=4.5, y0=4.2, r=.7), 
                       inherit.aes=FALSE, linetype=2) +
  geom_segment(aes(x=4.5, y=2.5, xend=4.5, yend=3.5),
               size=1, arrow=arrow(length=unit(0.5, "cm")))

精炼结果

enter image description here

注意:当然,您仍然可以对它进行优化,只是为了使您明白。

答案 1 :(得分:1)

对于这个问题,我建议使用另一种情节:

ggplot(example.data, aes(x=y.label, y = y)) + 
    geom_point() +
    geom_hline(yintercept = 4.1) +
    geom_text(aes(0,4.1,label = 4.1,hjust=-1,  vjust = -0.5))

Changed axis plot

相关问题