繁体   English   中英

注释 label 夹在 ggplot2

[英]Annotation label clipped in ggplot2

我试图避免底部注释被剪裁。 被砍掉的是“p”上的下降器。 我在 vjust 上使用了“向内”选项。

df <- data.frame(x=c(as.Date("2020-01-01"),as.Date("2022-01-01"))
                     ,y=c(0,1))
df
ggplot(df) +
  geom_point(mapping=aes(x=x,y=y)) +
  annotate("text",x=mean(df$x),y=-Inf,label="Clipped",hjust=0.5,vjust="inward",size=12,colour="red") +
  annotate("text",x=mean(df$x),y=Inf,label="Not Clipped",hjust=0.5,vjust="inward",size=12,colour="blue")

剪切的文本

一种可能的方法是使用minmax y 值:

library(tidyverse)

df <- data.frame(
  x = c(as.Date("2020-01-01"), as.Date("2022-01-01")),
  y = c(0, 1)
)

ggplot(df) +
  geom_point(aes(x, y)) +
  annotate("text", x = mean(df$x), y = min(df$y), label = "Clipped", hjust = 0.5, vjust = "inward", size = 12, colour = "red") +
  annotate("text", x = mean(df$x), y = max(df$y), label = "Not Clipped", hjust = 0.5, vjust = "inward", size = 12, colour = "blue")

代表 package (v2.0.1) 于 2022 年 7 月 2 日创建

有趣的。 看起来这个问题与选择什么作为基线来对齐文本标签有关。 当切换到geom_label时可以清楚地看到这一点,我们看到对于剪裁的 label,为 alignment 选择的基线不是“p”的结尾。 因此“p”被剪掉了:

ggplot(df) +
  geom_point(mapping = aes(x = x, y = y)) +
  annotate("label", x = mean(df$x), y = -Inf, label = "Clipped", 
           hjust = 0.5, vjust = "inward", size = 12, colour = "red", label.padding = unit(0, "lines")) +
  annotate("label", x = mean(df$x), y = Inf, label = "Not Clipped", 
           hjust = 0.5, vjust = "inward", size = 12, colour = "blue", label.padding = unit(0, "lines"))

在此处输入图像描述

一种可能的解决方法是切换到ggtext::GeomRichtext

library(ggplot2)
library(ggtext)

ggplot(df) +
  geom_point(mapping = aes(x = x, y = y)) +
  annotate(ggtext::GeomRichtext, x = mean(df$x), y = -Inf, label = "Clipped", 
           hjust = 0.5, vjust = "inward", size = 12, colour = "red", 
           label.size = 0, fill = NA, label.padding = unit(0, "lines")) +
  annotate(ggtext::GeomRichtext, x = mean(df$x), y = Inf, label = "Not Clipped", 
           hjust = 0.5, vjust = "inward", size = 12, colour = "blue", 
           label.size = 0, fill = NA, label.padding = unit(0, "lines"))

如果你不希望它被剪辑在同一个 position 上,你可以使用coord_cartesian(clip = "off")

df <- data.frame(x=c(as.Date("2020-01-01"),as.Date("2022-01-01"))
                 ,y=c(0,1))
library(ggplot2)
ggplot(df) +
  geom_point(mapping=aes(x=x,y=y)) +
  annotate("text",x=mean(df$x),y=-Inf,label="Clipped",hjust=0.5,vjust="inward",size=12,colour="red") +
  annotate("text",x=mean(df$x),y=Inf,label="Not Clipped",hjust=0.5,vjust="inward",size=12,colour="blue") +
  coord_cartesian(clip = 'off')

代表 package (v2.0.1) 于 2022 年 7 月 2 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM