【问题标题】:ggplot2 fix overlapping y-labelsggplot2 修复重叠的 y 标签
【发布时间】:2019-02-14 11:48:24
【问题描述】:

代码示例
让我举个小例子:

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 非常接近,因此标签会重叠:

信息
我为出版物绘制了一个非常相似的图表,并且不想仅仅为了使标签适合而增加图形的大小(这需要图表非常大)。我熟悉ggrepel,但据我所知,这仅适用于绘图本身内的文本注释,不适用于轴。

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

【问题讨论】:

  • y 轴真的是分类变量吗?在本例中,我将切换两个轴,这也是一种更自然的数据显示方式。像这样ggplot(example.data, aes(x=y.label, y = y)) + geom_point()

标签: r ggplot2 label axis-labels


【解决方案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()

结果

有了读者指南,它变得更加清晰:

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

优化结果

注意:当然,你仍然可以改进它,只是为了让你明白。

【讨论】:

    【解决方案2】:

    我会为这个问题建议一个不同的情节:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2020-09-20
      • 2021-01-22
      • 2020-11-14
      • 1970-01-01
      相关资源
      最近更新 更多