【问题标题】:Detecting programmatically whether axis labels overlap以编程方式检测轴标签是否重叠
【发布时间】:2020-11-19 06:16:43
【问题描述】:

有没有办法以编程方式检测ggplot2 中的轴标签是否重叠?

假设我创建了以下图表:

library(dplyr)
library(tibble)
library(ggplot2)

dt <- mtcars %>% rownames_to_column("name") %>% 
  dplyr::filter(cyl == 8)

ggplot(dt, aes(x = name, y = mpg)) + geom_point()

我想以编程方式检测 x 轴标签是否重叠并应用以下第一个补救措施:

ggplot(dt, aes(x = name, y = mpg)) + geom_point() +
  scale_x_discrete(guide = guide_axis(n.dodge = 2))

这是棘手的部分。假设尺寸不同,第一个补救措施也像这样重叠:

我想像这样应用第二种补救措施:

ggplot(dt, aes(x = name, y = mpg)) + geom_point() +
  theme(axis.text.x = element_text(angle=45, hjust = 1, vjust = 1)) 

是否可以不用肉眼检查图形?

【问题讨论】:

  • 是的,但这很复杂。标签是否重叠不仅取决于绘图代码 - 它还取决于绘图设备的尺寸。因此,任何代码都需要检查绘图设备的尺寸,如果您(或您的用户)调整绘图设备的大小,代码生成的绘图将不正确。
  • 我理解这个要求,但这可以通过coord_flip来解决:Y轴上的标签更长。
  • @AllanCameron,我同意这个困难,特别是如果情节尺寸可以改变(就像我在第二个和第三个情节之间所做的那样)。尽管如此,假设我们有一个固定大小的预定义输出维度,是否可以检测重叠的轴标签?例如,geom_text_repel() 对标签进行 AFIK。 @zx8754 是的,对于这些图表,coord_flip 可能是更好的选择。但是我关于检测重叠轴标签的更一般的问题仍然存在。

标签: r ggplot2


【解决方案1】:

不是一个确定的解决方案,但如果我们考虑边距不变,我们可以做一些简单的减法:

library(dplyr)
library(tibble)
library(ggplot2)

dt <- mtcars %>% rownames_to_column("name") %>% 
  dplyr::filter(cyl == 8)

p <- ggplot(dt, aes(x = name, y = mpg)) +
  geom_point()


# variable part
font_size <- 9 #points, the ggplot default
full_width <- 15 #cm
full_height <- 10 #cm

cm_to_pt <- 28.35 # 1 cm = 28.35 points

# try varying width
for(full_width in c(30, 40, 45, 50)){
  axis_text_length_pt <- ceiling(max(nchar(dt$name))/2)*font_size
  axis_available_pt <- full_width/n_distinct(dt$name)*cm_to_pt
  do_not_touch <- axis_text_length_pt <= axis_available_pt
  
  p +
    theme(axis.text.x = element_text(size=font_size)) +
    geom_text(aes(x=5,y=15, label=do_not_touch))
  ggsave(paste0("tmp_",full_width,".png"),
         width = full_width, height = full_height, unit = "cm")
}

在 40 厘米处,我们仍然可以看到 Hornet Sportabout 和 Lincoln Continental 接触,它们在 45 厘米处分开。

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多