【问题标题】:How to add a line under ggplot axis text如何在ggplot轴文本下添加一行
【发布时间】:2019-04-08 19:49:31
【问题描述】:

我想在 ggplot 底部添加一对水平线来说明 x 轴元素的分组。看起来geom_ablinegeom_segment 都会在图中添加线条。知道如何在其下添加线条吗?

p + geom_segment(aes(x = 2, y = -0.5, xend = 4, yend = -0.5 )) +
        geom_segment(aes(x = 5, y = -0.5, xend = 7, yend = -0.5)) 

这会在绘图中绘制线段,而不是在轴标题下方。

【问题讨论】:

  • ggplot 单独只能在绘图区域内做注释,但是几个扩展包可以让您在绘图区域外进行注释。我知道cowplot可以做到这一点,可能还有其他包也可以
  • 感谢您的信息。下面的答案很有用,但我会记住您的评论并尝试cowplot

标签: r ggplot2


【解决方案1】:

您可以使用coord_cartesian(xlim, ylim, clip="off") 在绘图区域外进行注释,然后使用annotate() 和适当的几何图形。根据您对分组的审美,您可以在绘图区域的底部或轴标签下方放置线条。

library(ggplot2)

df <- data.frame(x=seq(1,10), y=seq(1,10))

ggplot(df, aes(x,y)) +
  geom_point() +
  coord_cartesian(xlim=c(0,10), ylim=c(0,10), clip="off") +
  annotate("segment", x = 2, xend = 4, y = -1, yend = -1) +
  annotate("segment", x = 5, xend = 7, y = -0.5, yend = -0.5)

【讨论】:

  • 这很有帮助。谢谢。
  • @PDM,我很高兴。为了将来参考,可以将相同的方法应用于各种应用程序中的不同几何,如herehere 所述。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
相关资源
最近更新 更多