【问题标题】:Add vertical text in the top margin of ggplot在ggplot的上边距添加垂直文本
【发布时间】:2020-10-16 21:23:58
【问题描述】:

我有下面的情节代码

ggplot(na.omit(total), aes(x = day_after, y = use, group=t, na.rm=TRUE)) +
  geom_line(aes(linetype=t, color=t, na.rm=TRUE))+
  geom_point(aes(color=t, na.rm = TRUE)) +
  scale_color_manual(values=c("gray48", "indianred4"), labels=c("Treatment","Control")) +
  labs(x= "Days after beginning of deactivation period", y= "") +
  theme(panel.grid.minor = element_blank(),
        panel.background = element_blank()) +
  theme(panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_line( size=.1, color="grey"))+
  theme(legend.key=element_blank()) +
  guides(linetype = FALSE) +
  annotate('segment',x = 0,xend = 0,y = 0,yend = 60,size = 3,colour = "grey",
           alpha = 0.4) +
  annotate('segment',x = 7,xend = 7,y = 0,yend = 60,size = 3,colour = "grey",
                                 alpha = 0.4) +
  annotate('segment',x = 39,xend = 39,y = 0,yend = 60,size = 3,colour = "grey",
           alpha = 0.4) 
new_plot <- plot + theme(legend.title=element_blank(), legend.text = element_text(size=10),
      legend.position = "right")

我想要做的是在绘图之外的多个给定 (x,y) 值的顶部添加垂直文本。 Annotate_custom 有效,但它没有旋转文本的选项。基本上我试过 + annotation_custom(text_end,xmin=42,xmax=42,ymin=62,ymax=62) 这将是惊人的,只有我不能有像角度 = 90 这样的选项。 有什么帮助吗??

【问题讨论】:

    标签: r ggplot2 graph tidyverse


    【解决方案1】:

    可以使用annotation_custom,只要你关闭剪裁。您可以使用自定义grid::textGrob 来指定旋转。

    我没有您的数据,但使用内置 mtcars 数据集的示例应该足以说明。

    library(ggplot2)
    
    ggplot(mtcars, aes(disp, mpg)) + 
      geom_point() +
      geom_vline(xintercept = c(200, 400), size = 10, alpha = 0.05) +
      coord_cartesian(clip = "off") +
      theme_bw() +
      theme(plot.margin = margin(80, 20, 20, 20),
            panel.border = element_blank()) +
      annotation_custom(grid::textGrob("label 1", rot = 90), 
                        xmin = 200, xmax = 200, ymin = 40) +
      annotation_custom(grid::textGrob("label 2", rot = 90), 
                        xmin = 400, xmax = 400, ymin = 40)
    

    【讨论】:

    • 谢谢!!但是当我这样做时,文本一旦离开情节就会被删除......
    • 你记得把clip = "off"转入coord_cartesian吗?
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多